Building a comma separated list?

前端 未结 9 1481
说谎
说谎 2020-11-30 08:49

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 @         


        
9条回答
  •  星月不相逢
    2020-11-30 09:20

    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.

提交回复
热议问题