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?
Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)
From the menu bar, File → Save As. Next to “Format:”, click the drop-down menu and select “Comma Separated Values (CSV)” Click “Save”
A comma-separated list is produced for a structure array when you access one field from multiple structure elements at a time. For instance if S is a 5-by-1 structure array then S.name is a five- element comma-separated list of the contents of the name field.
Are you on SQL 2005? With props to Rob Farley who showed me this just recently:
SELECT stuff(( SELECT ', ' + cast(cat_id as varchar(max)) FROM categories FOR XML PATH('') ), 1, 2, '');
The inside query (with FOR XML PATH('')
) selects a comma-separated list of category IDs, with a leading ", ". The outside query uses the stuff function to remove the leading comma and space.
I don't have an SQL instance handy to test this, so it's from memory. You may have to play with the stuff parameters etc to get it to work exactly how you want.
COALESCE Returns the first nonnull expression among its arguments
First argument @output + ', '
is never null (unless you initialize @output
as null AND set CONCAT_NULL_YIELDS_NULL
to ON
), so it's always returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With