Concatenating strings containing NULL values - sql

I want to concatenate a string
I want output like this:
NEX-SYM-VIM-CRE
If the input is NEX-NULL-NULL-VRE, it comes out to be NEX---CRE or ---CRE or NEX--- as i have replaced NULL with -
But concatenation to get a final result like NEX-SYM is not coming

Something like this?
ISNULL(NEX,'-') + '-' + ISNULL(SYM,'-') + '-' + ISNULL(VIM,'-') + '-' + ISNULL(CRE,'-')

Always add a - delimiting character to the right but only when there is a value:
NULLIF(
COALESCE(NEX + '-', '')
+ COALESCE(SYM + '-', '')
+ COALESCE(VIM + '-', '')
+ COALESCE(CRE + '-', ''), ''
)
then you always need to trim the last character (will be a - delimiting character) unless the result is NULL.

Related

Need to concatenate 3 fields into one with carriage returns only when not null

I need to combine 3 address line fields into one formatted address block field with carriage returns between the lines only if line 2 and line 3 are not null.
The code I have now is:
replace(ADDRESSBLOCK,' ','') =
replace(coalesce(#ADDR2_1, '') + CHAR(13) + CHAR(10) +
coalesce(#ADDR2_2, '') + CHAR(13) + CHAR(10) +
coalesce(#ADDR2_3, ''),' ',''))
So for example if address line 1 equals 2014 Main St and address line 2 and 3 are null I get two extra carriage return lines in the result. I only want to conditionally have the carriage return lines if ADDR2 and/or ADDR3 are populated. Can anyone tell me how I might be able to do that in T-SQL?
Thanks in advance for your help
Try this SQL query:
SET addressblock = addr2_1
+ ISNULL(CHAR(13) + CHAR(10) + addr2_2, '')
+ ISNULL(CHAR(13) + CHAR(10) + addr2_3, '')
ISNULL will return true if there is a NULL anywhere in the evaluated text parameter.
SELECT ISNULL( ADD1 , '') +
ISNULL( CHAR(13)+CHAR(10) + ADD2 , '') +
ISNULL( CHAR(13)+CHAR(10) + ADD3 , '')

comma separated column values

I need to take the values from 3 columns and group them into 1 column as comma separated:
2014-01-01,2014-01-29
The problem is that one or more columns can be NULL and therefore it messes up the commas as such:
2014-01-01,,2014-01-29
This is how I have it coded (the case statement basically just strips out a comma if it's the last character in the string.
I need to add some logic so that it takes into account NULLs but I'm having a hard time coming up with it.
CASE WHEN RIGHT(ISNULL(d.FirstGapDate + ',', '') + ISNULL(d.PayrollGapDate + ',', '') + d.LastGapDate, 1) = ','
THEN LEFT(ISNULL(d.FirstGapDate + ',', '') + ISNULL(d.PayrollGapDate + ',', '') + d.LastGapDate, LEN(ISNULL(d.FirstGapDate + ',', '') + ISNULL(d.PayrollGapDate + ',', '') + d.LastGapDate) - 1)
ELSE ISNULL(d.FirstGapDate + ',', '') + ISNULL(d.PayrollGapDate + ',', '') + d.LastGapDate
END AS AlLGapDatesFormatted
EDIT -
I need to group the highlighted (notice that PayrollGapDate is ''):
And this is what I'm getting:
And this is the code I implemented:
try using this technique:
SET CONCAT_NULL_YIELDS_NULL ON --<<<make sure concatenations with NULL result in NULL
DECLARE #C1 varchar(10)='AAA'
,#C2 varchar(10)='BBB'
,#C3 varchar(10)=null
,#C4 varchar(10)='DDD'
SELECT STUFF( ISNULL(', '+#C1,'')
+ISNULL(', '+#C2,'')
+ISNULL(', '+#C3,'')
+ISNULL(', '+#C4,'')
,1,2,''
)
output:
-----------------------------------------------
AAA, BBB, DDD
(1 row(s) affected)
You let the ', '+#C3 result in NULL, which the ISNULL(***,'') converts to empty string. The STUFF(***,1,2,'') removes the leading comma and space.
try:
SELECT STUFF( ISNULL(', '+d.FirstGapDate,'')
+ISNULL(', '+d.PayrollGapDate,'')
+ISNULL(', '+d.LastGapDate,'')
,1,2,''
)
FROM ...
WHERE...
You can apply something like this above your expression to replace many commas with one comma:
declare #s varchar(100) = 'ABC,,,,DEF'
select replace(replace(replace(#s, ',', '[]'), '][', ''), '[]', ',')

Concatenate and format text in SQL

I need to concatenate the City, State and Country columns into something like City, State, Country.
This is my code:
Select City + ', ' + State + ', ' + Country as outputText from Places
However, because City and State allow null (or empty) value, what happen is, (for example) if the City is null/empty, my output will look like , Iowa, USA; or say the State is empty, then the output will look like Seattle, , USA
Is there anyway I can format the output and remove "unnecessary" commas?
Edited: Because of the requirements, I should not use any other mean (such as PL/SQL, Store Procedure) etc., so it has to be plain SQL statement
select
isnull(City, '') +
case when isnull(City, '') != '' then ', ' else '' end +
isnull(State, '') +
case when isnull(State, '') != '' then ', ' else '' end +
isnull(Country, '') as outputText
from
Places
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result
Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places
Use the COALESCE (Transact-SQL) function.
SELECT COALESCE(City + ', ', '') + COALESCE(State + ', ', '')...
In SQL Server 2012 you can use CONCAT function:
select concat(City,', ',State,', ',Country ) as outputText from Places
Not elegant by any means...
first changes city, state,country to null values if blank
then interprets that value for null and adds a space before a comma
then replaces any space comma space ( , ) with empty set.
Query:
SELECT replace(coalesce(Replace(City,'',Null),' ') + ', ' +
coalesce(Replace(State,'',Null), ' ' + ', ' +
coalesce(replace(Country,''Null),''), ' , ','') as outputText
FROM Places
Assumes no city state or country will contain space comma space.

simplifying a LEFT / REPLACE query

I have a query that is in dire need of being simplified. Here is part of the query:
SELECT
LEFT(MLIS.REQUESTOR_FIRST_NAME, CharIndex( ' ', MLIS.REQUESTOR_FIRST_NAME + ' ' ) - 1)
, CharIndex( ' ', LEFT(MLIS.REQUESTOR_FIRST_NAME, CharIndex( ' ', MLIS.REQUESTOR_FIRST_NAME + ' ' ) - 1) + ' ' ) - 1)
+REPLICATE(' ',25),25)+
LEFT(' '+REPLICATE(' ',20),20)+
LEFT(
LEFT(
LEFT(MLIS.REQUESTOR_LAST_NAME, CharIndex( ',', MLIS.REQUESTOR_LAST_NAME + ',' ) - 1)
, CharIndex( ',', LEFT(MLIS.REQUESTOR_LAST_NAME, CharIndex( ',', MLIS.REQUESTOR_LAST_NAME + ',' ) - 1) + ',' ) - 1)
the reason I am doing the replicates is because i am building a fixed length string. each column needs to be a fixed length.
in addition to the above query, for every occurrence of MLIS.REQUESTOR_FIRST_NAME and MLIS.REQUESTOR_LAST_NAME i need to do:
REPLACE(REPLACE(MLIS.REQUESTOR_FIRST_NAME,', MD',''),',MD','')
and
REPLACE(REPLACE(MLIS.REQUESTOR_LAST_NAME,', MD',''),',MD','')
How do I include these REPLACES in the query and simplify the entire thing?
thanks so much for your guidance and kind help.
select the common bits in a subquery... (you'll have a bit more)
SELECT
LEFT(REQUESTOR_FIRST_NAME, fname_idx - 1)
, CharIndex( ' ', LEFT(MLIS.REQUESTOR_FIRST_NAME, fname_idx - 1) + ' ' ) - 1)
..
FROM ( select CharIndex( ' ', MLIS.REQUESTOR_FIRST_NAME + ' ' ) fname_idx, REQUESTOR_FIRST_NAME from...
Using a subquery will help with the syntax. In addition, you can cast to a CHAR() to pad and truncate strings to a given length.
I think the following does what you want:
SELECT cast(fname as char(25)) + ' ' + cast(lname as char(25))
from (select replace(replace(LEFT(MLIS.REQUESTOR_FIRST_NAME,
CharIndex(' ', MLIS.REQUESTOR_FIRST_NAME + ' ' ) - 1
),
',MD', ''),
', MD', '') as fname,
replace(relpace(left(MLIS.REQUESTOR_LAST_NAME,
CharIndex(',', MLIS.REQUESTOR_LAST_NAME + ',' ) - 1),
CharIndex(',', LEFT(MLIS.REQUESTOR_LAST_NAME,
CharIndex( ',', MLIS.REQUESTOR_LAST_NAME + ',' ) - 1) + ','
) - 1
),
',MD', ''),
', MD', '') as lname
However, it is hard to follow the original query, and there might be a syntax error. This query is meant to give you some guidance on solving the problem. I would also put a cast after the concatenate to be sure the final string is the right length.

What's the shortest TSQL to concatenate a person's name which may contain nulls

3 fields: FirstName, MiddleName, LastName
Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.
LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' +
LTRIM(ISNULL(LastName, ''))
))
NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.
Assuming by "extra spaces", you mean extra spaces inserted during the concatenation (which is a reasonable assumption, I think. If you have extra spaces in your data, you should clean it up):
ISNULL(FirstName + ' ', '') + ISNULL(MiddleName + ' ', '') + ISNULL(LastName, '')
works, since you'll add a space to the name - which if it's NULL yields NULL - which yields empty string.
Edit: If you don't count the SET OPTION - which can be a connection or db option:
SET CONCAT_NULL_YIELDS_NULL OFF
LTRIM(FirstName + ' ' + NULLIF(MiddleName + ' ', ' ') + LastName)
is a tiny bit shorter, but a large bit uglier.
Edit2: Since you accepted the UDF answer - IMO, that's a bit of a cheat - here's some in the same vein:
SELECT a FROM b
b is a view. ;) Or. a stored proc,
EXEC c
But, since EXEC is optional:
c
use a UDF:
`Select udfConcatName(First, Middle, Last) from foo`
That way all your logic for concatenating names is in one place and once you've gotten it written it's short to call.
LTRIM(RTRIM(ISNULL(FirstName, '') + ' ' + LTRIM(ISNULL(MiddleName, '') + ' ' +
ISNULL(LastName, ''))))
Why not use a computed column on the table that performs the concat for you using your preferred syntax from the many posted here? Then you will just query the computed column - very elegant and if you persist the computed column then you may even get slight performance increase.
Example here
replace(ltrim(rtrim(isnull(FirstName, '') + ' ' + isnull(MiddleName, '') + ' ' + isnull(LastName, ''))), ' ', ' ')
'"' + ltrim(rtrim(isnull(FirstName,''))) + ' ' + ltrim(rtrim(isnull(MiddleName,''))) +
' ' + ltrim(rtrim(isnull(LastName,''))) + '","' + ltrim(rtrim(isnull(FirstName,''))) +
' ' + ltrim(rtrim(isnull(LastName,''))) + '","' + ltrim(rtrim(isnull(LastName,''))) +
'"'
ETC
DECLARE #first varchar(10) = 'First'
DECLARE #middle varchar(10) = ''
DECLARE #last varchar(10) = 'Last'
LTRIM(RTRIM(
#first
+ ISNULL(NULLIF(' '+LTRIM(RTRIM(#middle)),' '),'')
+ ISNULL(NULLIF(' '+LTRIM(RTRIM(#last)),' '),'')
))
WHY THIS WORKS
The fields are reduced to an empty string if NULL or whitespace by the LTRIM, RTRIM, and ISNULL functions.
LTRIM(RTRIM(ISNULL(#middle,''))) -- Result is a trimmed non-null string value.
That value is prefixed with a single space, then compared to a single space by the NULLIF function. If equal, a NULL results. If not equal, then the value is used.
NULLIF(' '+'',' ') -- this would return NULL
NULLIF(' '+'Smith',' ') -- this would return ' Smith'
Finally, ISNULL() is used to convert the NULL passed by NULLIF to an empty string.
ISNULL(NULL,'') -- this would return ''
ISNULL(' Smith','') -- this would return ' Smith'
LTrim(RTrim(Replace(IsNull(Firstname + ' ', '') +
isNull(MiddleName, '') +
IsNull(' ' + LastName, ''), ' ', ' ')))
Select firstname, middlename, lastname, ProvidedName =
RTrim(Coalesce(FirstName + ' ','')
+ Coalesce(MiddleName + ' ', '')
+ Coalesce(LastName + ' ', '')
+ COALESCE('' + ' ', '')
+ COALESCE(NULL, ''))
From names