select isnull(column1,'')+','+isnull(column2,'')+','+isnull(column3,'') AS column4 from table
From the above query, I get what I need, which is really good. But the fact is that if all the columns are all NULL, I get the commas that I used to separate the fields.
NULL
I want the comma to be replaced by NULLwhen every field NULL. Can someone help me with this? thanks!
You can pack + ','inISNULL()
+ ','
ISNULL()
select isnull(column1+',','')+isnull(column2+',','')+isnull(column3,'') AS column4 from table
You can do this using the stuff()following:
stuff()
select stuff((coalesce(',' + col1, '') + coalesce(',' + col2, '') + coalesce(',' + col3, '') ), 1, 1, '')
Other databases often have a function named concat_ws()that also does this.
concat_ws()
CASE EXPRESSION:
SELECT CASE WHEN column1 is not null then column1 + ',' else '' end + CASE WHEN column2 is not null then column2 + ',' else '' end + CASE WHEN column3 is not null then column3 else '' end as column4
First, count the number of spaces in the name and add it to the counter, and you will get the result. You can also trim the string if necessary
declare @count as int declare @spaceCount as int select @count =(LEN('amjad habib')) select @spaceCount =@count-LEN(REPLACE('amjad habib', ' ', '')) SELECT SUBSTRING('amjad habib',1 , 8 + @spaceCount )