Concatenation of strings by for xml path

后端 未结 2 1503
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 04:18

Hi! Today I learned for xml path technique to concatenate strings in mssql. Since I\'ve never worked with xml in mssql and google hasn\'t helped, I need to ask

相关标签:
2条回答
  • 2021-01-14 04:55

    Your subquery cannot return two values. If you just want to concatenate strings, you do not need the xml data type at all. You can do the stuff() and subquery in a single statement:

    declare @Rep1Names nvarchar(max) = (
        stuff((select ', [' + report_name + ']' as name
               from (select distinct report_order, report_name
                     from #report
                    ) x
               order by report_order
               for xml path('')
              )
             ), 1, 1, '');
    
    declare @Rep2Names nvarchar(max) = (
        stuff(select ', isnull([' + report_name + '], 0) as [' + report_name + ']' as res
               from (select distinct report_order, report_name
                     from #report
                    ) x
               order by report_order
               for xml path('')
              )
       ), 1, 1, '');
    
    0 讨论(0)
  • 2021-01-14 04:58

    Ok, so I haven't been completely satisfied the way Gordon Linoff suggested and since I've found this kind of problem actual for me I'm adding here another solution without using for xml path:

    declare
        @pivot_sequence nvarchar(max),
        @columns_sequence nvarchar(max)
    
    select
        @pivot_sequence = coalesce(@pivot_sequence + ', [', '[') 
            + col_name + ']',
        @columns_sequence = coalesce(@columns_sequence + ', ', '')
            + 'isnull([' + col_name + '], 0) as [' + col_name + ']'
    from some_table
    order by
        /* some_columns if needed to order concatenation */
    

    Obviously, it'll work much slower but in cases when you haven't many rows it won't drastically affect on performance. In my case I have dynamic pivot query and these strings are built for it - I won't have many columns in pivot so it's fine for me.

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