Building a comma separated list?

前端 未结 9 1440
说谎
说谎 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:27
    declare     @output varchar(max)
    
    select      @output = coalesce
                          ( 
                              @output + ', ' + convert(varchar(max),cat_id), 
                              convert(varchar(max),cat_id)
                          )
    from        yourTableHere
    
    print       @output
    
    0 讨论(0)
  • 2020-11-30 09:40

    And sometimes...

    you have to answer your own question

    declare     @output varchar(max)
    select      @output = case when (@output is null) then '' else ', ' END + convert(varchar(max),cat_id)
    
    0 讨论(0)
  • 2020-11-30 09:42

    check @output value just before the execution of this query, I think it's not equal to NULL 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 old CASE WHEN:

    select @output = NULL
    select @output = CASE WHEN @output IS NULL THEN '' ELSE @output+', ' END + value
    
    0 讨论(0)
提交回复
热议问题