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