Building a comma separated list?

前端 未结 9 1439
说谎
说谎 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:18

    Did you initialize @output to an empty string? COALESCE will only work if it's a NULL string.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 09:21

    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/

    0 讨论(0)
  • 2020-11-30 09:23

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

    0 讨论(0)
  • 2020-11-30 09:24

    On Unix, the sqlminus command lets you merge SQL commands and other formatting:

    % sqlminus "select ri || ',' ||name|| ',' || numports || ',' || ascii(OVRONSET) from sdfctigw.ivrgrp where GRP_BEP is not null;" | sort -h
    1,COMO INTERNAL 2,700,90
    7,LOADIVR,10,80
    10,SPEECH_IVR_PROD,600,95
    
    0 讨论(0)
  • 2020-11-30 09:25

    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.

    0 讨论(0)
提交回复
热议问题