5

I am currently working on a query which join multiple columns in to 1 string with comma (,) as a separator between each other. I'm unable to figure out how to deal with null values.

DECLARE 
    @item1 nvarchar(max) = 'a',
    @item2 nvarchar(max) = 'b',
    @item3 nvarchar(max) = 'c'

SELECT CONCAT(
    ISNULL(NULLIF(@item1, '') + ', ', ''), 
    ISNULL(NULLIF(@item2, '') + ', ', ''), 
    ISNULL(NULLIF(@item3, ''), '')
)

--@item1 = 'a', @item2 = 'b', @item3 = 'c'
--Output : a, b, c

--@item1 = 'a', @item2 = NULL, @item3 = 'c'
--Output : a, c

--@item1 = NULL, @item2 = 'b', @item3 = 'c'
--Output : b, c

With the code above it works well when @item1 or @item2 even both are NULL value, but there is a problem if @item3 is NULL value, it will have an extra comma(,) at the end,

--@item1 = 'a', @item2 = 'b', @item3 = NULL
--Output : a, b,

--@item1 = 'a', @item2 = NULL, @item3 = NULL
--Output : a,

I know this is because I hard coded the comma(,) on the NULLIF statement for @item1 and @item2, but I can't figure out there is any other better way to do this.

Any advise or a better solution for this problem?

1

3 Answers 3

9

The STUFF method is probably the better option here:

STUFF(CONCAT(',' + NULLIF(@item1, ''),',' + NULLIF(@item2, ''),',' + NULLIF(@item3, '')),1,1,'')
Sign up to request clarification or add additional context in comments.

Comments

2

Simpler than STUFF, use CONCAT_WS:

CONCAT_WS(', ', NULLIF(@item1,''), NULLIF(@item2,''), NULLIF(@item3,''))

Comments

0

Here you can use, the concat operator, for the first variable don't pass concat separator, from second variable onwards pass the concat variable (separator) before variable...

declare @a varchar(10)='a'
declare @b varchar(10)='b'
declare @c varchar(10)=null
select isnull(@a,'')+isnull(','+@b,'')+isnull(','+@c,'')

1 Comment

This doesn't return the result the OP wants if any of the values have the value '' or NULL.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.