Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server concatenation separated by comma only when column is not null

I have the following SQL statement:

@All = COALESCE(NULLIF(@Asc1, '') + ',', '') +
        OALESCE(NULLIF(@Asc2, '') + ',', '') +
        OALESCE(NULLIF(@Asc3, '') + ',', '');

This will insert a comma at the end even if any of the variables (@Asc1, @Asc2, @Asc3) have NULL or empty values.

For example:

  • if @Asc1 = 1234 and @Asc2 = 3456 and @Asc3 = '', then @All will end up being 1234,3456,

I would like @All to be 1234,3456

Thanks.

like image 948
Eclipse Avatar asked Mar 08 '23 15:03

Eclipse


1 Answers

using stuff() to remove the first comma and reversing the comma concatenation:

set @all = stuff(
    coalesce(','+nullif(@Asc1, ''), '')
  + coalesce(','+nullif(@Asc2, ''), '')
  + coalesce(','+nullif(@Asc3, ''), '')
  ,1,1,'');

rextester demo: http://rextester.com/UNDS90887

returns: 1234,3456

like image 50
SqlZim Avatar answered Mar 11 '23 00:03

SqlZim