Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a comma separated list?

Tags:

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?

like image 370
pablo Avatar asked Oct 14 '09 08:10

pablo


People also ask

How do I convert Excel Columns to comma-separated lists?

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.)

How do I convert a CSV file to a comma-separated list?

From the menu bar, File → Save As. Next to “Format:”, click the drop-down menu and select “Comma Separated Values (CSV)” Click “Save”

What are comma-separated lists?

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.


2 Answers

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.

like image 99
Matt Hamilton Avatar answered Oct 25 '22 08:10

Matt Hamilton


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.

like image 32
The Chairman Avatar answered Oct 25 '22 07:10

The Chairman