AS NewCompoundField - Concatenating values which may be NULL - sql

I have the following T-SQL query;
SELECT
Site.Address1 + CHAR(13) + Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
If any of the Site.AddressX fields making up SiteAddress are NULL, then SiteAddress is itself NULL. I would like a Site.AddressX field and it's following new line character to be ignored if it is NULL.
I have tried adding a CASE statement for a single field and it's new line character, but have not been able to get it to work.
SELECT
(CASE WHEN (Site.Address1 IS NULL) THEN '' ELSE Site.Address1 + CHAR(10)) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
How might I go about doing this?

Try this:
SELECT
COALESCE([Site].Address1 + CHAR(13), '') +
COALESCE([Site].Address2 + CHAR(13), '') +
COALESCE([Site].Address3 + CHAR(13), '') +
COALESCE([Site].Town + CHAR(13), '') +
[Site].eCounty AS SiteAddress
FROM [Site]

Try this
SELECT
CASE WHEN Site.Address1 IS NULL THEN ''
ELSE Site.Address1 + CHAR(10) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty END AS SiteAddress
FROM SITE Site

Related

sql server 2012 : Incorrect syntax near the keyword 'else'

I receive this error and I cant find out why.
case when FormFields.fieldtype like '%date%'
then 'not' + fieldname + ' is null and ( convert(datetime,'
+ fieldname +',103) < '
+ coalesce(str(FormFields.MinDate),'1/1/1900') + ')'
+ ' or ( convert(datetime,' + fieldname +',103) > '
+ coalesce(str(FormFields.MaxDate), '1/1/2200') + ')'
+
else
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
+
end
previous code without any error:
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
+
I just wanted to add another case
You have 2 extra + in your query, 1 in the end of the THEN part, another in end of the ELSE part. If you need to combine CASE expression with another string, use + after END. Try in following:
case when FormFields.fieldtype like '%date%'
then 'not' + fieldname + ' is null and ( convert(datetime,'
+ fieldname +',103) < '
+ coalesce(str(FormFields.MinDate),'1/1/1900') + ')'
+ ' or ( convert(datetime,' + fieldname +',103) > '
+ coalesce(str(FormFields.MaxDate), '1/1/2200') + ')'
else
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
end
+ 'Any string after CASE expression'

using sql - Is not null in a select statement

I can't seem to figure out how to use the opposite of isnull or ifnull statements in sql. I need to say if a.Error1 is not null -- then print the ' - ' and the + CHAR(13)+CHAR(10). Basically There should be no dash or no new line break if the a.Error1 comes back null. So print the information if the field isn't null.
select a. ....
' - ' + a.Error1 + CHAR(13)+CHAR(10) +
' - ' + a.Error2 + CHAR(13)+CHAR(10) +
' - ' + a.Error3 + CHAR(13)+CHAR(10) +
' - ' + a.Error4 + CHAR(13)+CHAR(10) +
' - ' + a.Error5 + CHAR(13)+CHAR(10) +
' - ' + a.Error6 as 'error_message'
...
from table1 a
For example if for a given record error1, 2 and 5 returned output I would like the output to be as follows:
- Error1: There was a ...
- Error2: ....
- Error5: The data was ...
If no errors existed for that row it should simply be an empty/null field.
You can use CASE:
SELECT a. ....
(CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error3 IS NOT NULL
THEN ' - ' + a.Error3 + CHAR(13)+CHAR(10)
ELSE ''
END) +
...etc
Yes! i know i'm like 5 years too late but i too enountered this problem.
It's weird how it doesn't exist some kind of !ISNULL() but whatever.
Try this for a cleaner code:
select a. ....
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error1,
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error2
from table1 a
Learn more about IIF() function : SQL Server IIF Function
The COALESCE function does what you want here. The result of COALESCE is the first NOT NULL value it is passed. Below we use '', which is distinct from NULL so that the outer + is always applied to NOT NULL strings.
e.g.
select a. ....
COALESCE( ' - ' + a.Error1 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error2 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error3 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error4 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error5 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error6 , '' ) as 'error_message'
...
from table1 a
SELECT (CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10) +
ELSE a.Error1
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10) +
ELSE a.Error2
END) +
.....etc

How to write/append text to the bottom of n SQL script?

I have the need to add/append text(SQL) to the bottom of an existing script.
I have a STORED PROCEDURE that generates INSERT statements for me. They are quit allot, so at the moment i copy and past them in the desired scripts.
This is basically what the SQL looks like:
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + '; '
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
With an output of:
EXECUTE [procSystemAppEntity_InsertOrUpdate]
#SystemUID = #SystemUID
,#SystemAppCode = #SystemAppCode
,#SystemAppEntityTypeCode = N'App-S'
,#SystemAppEntityUID = '11E347C7-7E69-4555-A6F0-2AFE142FC25F'
,#SystemAppEntityCode = 'Revision'
,#SystemAppEntityName = N'Revision'
,#TableName = N'Revision'
,#TableKeyColumnName = N'RevisionID'
,#TableKeyCodeColumnName = N'RevisionCode'
,#ManagedAssemblyName = N'SomeManagedAssemblyName '
, #ManagedNamespace = N'SomeManagedNamespace '
, #ManagedClassName = 'Revision'
, #IsMultiple = 0
, #IsCodeGenerated = 1
, #IsIntegratedToStaging = 1
, #IsActive = 1
, #SystemAppUserID = #CreationSystemAppUserID
;
That being said, is there a way that i can maybe write/append the Output statements directly to the desired script?
I just want it to add to the bottom of the script. Is this possible and if so, how would i achive this?
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + ';
Insert into table(...) ;'
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
What version of SQL Server are you using?
If you are using SQL Server 2008+ then you can make generate the INSERT scripts via Generate Script utility itself.
In SQL Server 2005 or before (I have tried in SQL 2K also) then there is a pretty good stroed proc which can generate the INSERT script for a given table. Check out http://vyaskn.tripod.com/code/generate_inserts.txt

SQL results to Outlook VCard?

I need to export SQL records to outlook vcards, so 1 vcard per result row returned. Does anyone know how to do this?
Maybe something like this:
DECLARE #crlf char(2)
SET #crlf = CHAR(13) + CHAR(10)
SELECT
'BEGIN:VCARD' + #crlf
+ COALESCE ('N:' + COALESCE (Last, '') + ';'
+ COALESCE (First, '') + ';'
+ COALESCE (Mi, '') + #crlf, '')
+ COALESCE ('FN:' + FullName + #crlf, '')
+ COALESCE ('TITLE:' + Title + #crlf, '')
+ COALESCE ('ORG:' + Company + #crlf, '')
+ COALESCE ('TEL;WORK;VOICE:' + PhoneWork + #crlf, '')
+ COALESCE ('TEL;WORK;FAX:' + FaxWork + #crlf, '')
+ COALESCE ('TEL;HOME;VOICE:' + [PhoneHome] + #crlf, '')
+ COALESCE ('TEL;HOME;FAX:' + [FaxHome] + #crlf, '')
+ COALESCE ('TEL;CELL;VOICE:' + [PhoneMobile] + #crlf, '')
+ COALESCE ('TEL;PAGER;VOICE:' + [Pager] + #crlf, '')
+ 'ADR;WORK:;;' + COALESCE ([Address], '') + ';'
+ COALESCE ([City], '') + ';' + COALESCE ([State], '') + ';'
+ COALESCE ([Zip], '') + #crlf
+ COALESCE ('EMAIL;PREF;INTERNET:' + [email] + #crlf, '')
+ 'REV:' + { fn REPLACE({ fn REPLACE(
{ fn REPLACE(CONVERT(varchar, GETDATE(), 120), '-', '')
}, ':', '') }, ' ', 'T') } + 'Z'+ #crlf
+ 'END:VCARD' + #crlf AS vcard
FROM
yourTable

How to concatenate strings and commas in SQL Server?

I'm relatively new to MSSQL, so sorry if the question might sounds trivial. I want to concatenate multiple fields with a delimiter ,. However, when the field is empty, the extra , will be included in the result string as well. So is there an easy way to solve this problem? For example,
SELECT VRI.Street_Number_and_Modifier + ',' +
VRI.Street_Direction + ',' +
VRI.Street_Name + ',' +
VRI.Street_Direction + ',' +
VRI.Street_Suffix + ',' +
VRI.Street_Post_Direction + ',' +
VRI.Unit
FROM View_Report_Information_Tables VRI
This modified version of Lamak's handles NULL or strings containing only space/empty:
SELECT COALESCE(NULLIF(VRI.Street_Number_and_Modifier, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Name, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Suffix, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Post_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Unit, ''), '')
FROM View_Report_Information_Tables VRI
I was able to get it to work with a slightly different approach. Putting the commas at the beginning of each field and then removing the first one with the STUFF function worked for me:
SELECT
STUFF((COALESCE(', ' + NULLIF(VRI.Street_Number_and_Modifier, ''), '') +
COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '') +
COALESCE(', ' + NULLIF(VRI.Street_Name, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Suffix, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Post_Direction, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Unit, ''), ''))
, 1, 2, '')
FROM View_Report_Information_Tables AS VRI
If the columns are empty instead of null, you can try this:
SELECT VRI.Street_Number_and_Modifier
+ CASE WHEN VRI.Street_Number_and_Modifier <> '' THEN ', ' ELSE '' END
+ VRI.Street_Direction
+ CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Street_Name
+ CASE WHEN VRI.Street_Name <> '' THEN ', ' ELSE '' END
+ VRI.Street_Direction
+ CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Street_Suffix
+ CASE WHEN VRI.Street_Suffix <> '' THEN ', ' ELSE '' END
+ VRI.Street_Post_Direction
+ CASE WHEN VRI.Street_Post_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Unit
+ CASE WHEN VRI.Unit<> '' THEN ', ' ELSE '' END
FROM View_Report_Information_Tables VRI
For SQL 2008+
Using
ISNULL(Colmn1 + ', ', '')
Will always result with a leading comma in the end, so you'll have to handle it.
Example:
DECLARE #Column1 NVARCHAR(10) = 'Column1'
, #Column2 NVARCHAR(10) = 'Column2'
SELECT SUBSTRING( ISNULL(#Column1 + ', ', '') + ISNULL(#Column2 + ', ', '')
, 0 --Starting from 0 not 1 to remove leading comma
, LEN(ISNULL(#Column1 + ', ', '') + ISNULL(#Column2 + ', ', '')))
Or we could approach this the other way around and use the STUFF function to remove our beginning comma which looks cleaner, example:
SELECT STUFF (ISNULL(( ', ' + #Column1), '') + ISNULL(( ', ' + #Column2), ''), 1, 2, N'')
For SQL 2012+ we could use the CONCAT function and remove beginning comma using STUFF similar to our previous example but avoiding ISNULL:
SELECT STUFF(CONCAT( ', ' + #Column1, ', ' + #Column2), 1, 2, N'')
For SQL 2017+ CONCAT_WS was introduced where you can concatinate/join multiple string columns with a delimiter specified in the first argument of the function:
MS Documents CONCAT_WS
MS Doc Example:
SELECT CONCAT_WS(',' --delimiter
,'1 Microsoft Way', NULL, NULL, 'Redmond', 'WA', 98052) AS Address;
Try this:
SELECT COALESCE(VRI.Street_Number_and_Modifier + ',','') +
COALESCE(VRI.Street_Direction + ',','') +
COALESCE(VRI.Street_Name + ',','') +
COALESCE(VRI.Street_Direction + ',','') +
COALESCE(VRI.Street_Suffix + ',','') +
COALESCE(VRI.Street_Post_Direction + ',','') +
COALESCE(VRI.Unit,'')
FROM View_Report_Information_Tables VRI
Short or long answer?
Short answer - dont. This is a formatting issue, not a database issue.
Long answer - When you concatenate a string and a null in sql server, the result is null. So you can use combinations of ISNULL
SELECT ISNULL(afield + ',','') + ISNULL(bfield + ',','')
You have to use select case when IsNull(fieldname, '')= '' or ltrim(rtrim(fieldname))='') Then ... Else... end +...
Edit:
Was written from Android mobile.
Below your example.
The following translations (from German) apply, FYI:
Vorname: given name
Name: surname
Benutzer: User
And here's the example code:
CREATE VIEW [dbo].[V_RPT_SEL_Benutzer]
AS
SELECT
BE_ID AS RPT_UID,
CASE
WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '') AND (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
THEN ''
WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '')
THEN ISNULL(BE_Vorname, '')
WHEN (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
THEN ISNULL(BE_Name, '')
ELSE
ISNULL(BE_Name, '') + ', ' + ISNULL(BE_Vorname, '')
END AS RPT_Name,
ROW_NUMBER() OVER (ORDER BY BE_Name, BE_Vorname ASC) AS RPT_Sort
FROM T_Benutzer
You could use the ISNULL(field + ',', '')
SELECT isnull(VRI.Street_Number_and_Modifier + ',','')+
isnull(VRI.Street_Direction + ',','')+
isnull(VRI.Street_Name + ',','')+
isnull(VRI.Street_Direction + ',','')+
isnull(VRI.Street_Suffix + ',','')+
isnull(VRI.Street_Post_Direction + ',','')+
isnull(VRI.Unit,'')
FROM View_Report_Information_Tables VRI
I would agree completely with Jamiec's short answer.
Otherwise, I would look at a nasty solution of using a REPLACE([concat], ',,', ',') everywhere you concatenate two columns, and then figure out how to trim commas from the beginning and end of the string where the first and last columns might be empty. Very very messy.
Wanted to see if I can get it without using CASE but could not. A long-winded way of mine:
SELECT case when isnull(nullif(VRI.Street_Number_and_Modifier, ''),'')='' then '' else VRI.Street_Number_and_Modifier end
+ case when isnull(nullif(VRI.Street_Direction, ''),'')='' then '' else ',' + VRI.Street_Direction end
+ case when isnull(nullif(VRI.Street_Name, ''),'')='' then '' else ',' + VRI.Street_Name end
+ case when isnull(nullif(VRI.Street_Suffix, ''),'')='' then '' else ',' + VRI.Street_Suffix end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
FROM View_Report_Information_Tables VRI
SELECT COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_1_TXT, ''), ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_2_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_3_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CITY_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ST_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CNTRY_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_PSTL_CD, '') , '')
FROM ACCOUNT_DETAILS ad
This will not add any commas if null-strings
SELECT CONCAT_WS(', ', IFNULL(column1, NULL),
IFNULL(column2, NULL), IFNULL(column3, NULL),
IFNULL(column4, NULL), IFNULL(column5, NULL))
FROM yourtable