I'm tryin to use SQL to build a comma separated list of cat_id's
the code is:
declare @output varchar(max)
set @output = null;
select @output = COALESCE(@output + ', ', '') + convert(varchar(max),cat_id)
edit: changed '' to null, STILL same. but the output im getting is like so:
, 66 , 23
the leading comma should not be there. What have i missed?
And sometimes...
you have to answer your own question
Not sure if this applies exactly to what you're looking for, but I found this right at the same time I found your questions. I use the second solution with FOR XML PATH, which Matt Hamilton mentioned above. It's worked great for me.
Concatenating Rows - By Carl P. Anderson, 2009/10/14
http://www.sqlservercentral.com/articles/T-SQL/67973/
COALESCE Returns the first nonnull expression among its arguments
First argument
@output + ', '
is never null (unless you initialize@output
as null AND setCONCAT_NULL_YIELDS_NULL
toON
), so it's always returned.What you are doing wrong is that @output is not null from start, but an empty string. Set @output to null before the loop (or if it's not used since it's declared just don't assign an empty string to it).
check
@output
value just before the execution of this query, I think it's not equal toNULL
but to '' (empty string)EDIT: (after the @auth edited the question)
now I'm sure it's '',
you have to initialize it to
NULL
to do it independently of
CONCAT_NULL_YIELDS_NULL
, use the oldCASE WHEN
: