Concatenation of strings by for xml path

后端 未结 2 1506
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题