sql server - Convert Tsql query result from rows to column names with other rows as column data -
i use query result :
declare @mag int = 237006 ;with res ( select mnf.filetypeid magtype, mnf.insertdate magdate, mnf.star, nl.logtype, nl.insertdate logdate magazinenumberfiles mnf left outer join nomags_log nl on nl.magazinenumberid = mnf.magazinenumberid mnf.magazinenumberid = @mag ) select * res
result of query is:
magtype magdate star logtype logdate 2 2013-04-13 * 7 2013-04-16 6 2013-04-14 * 3 2013-04-17 8 2013-04-15 null null null
i want convert result :
magtype2 magstar2 magtype6 magstar6 magtype8 magstar8 logtype7 logtype3 2013-04-13 * 2013-04-14 * 5 null 2013-04-16 2013-04-17
how can using tsql ?
you can, ugly dynamic sql:
declare @sql nvarchar(max) = ''; select @sql = 'select ' + stuff((select ',''' + convert(varchar,magdate) + ''' magtype' + convert(varchar,magtype) + char(10) + isnull(',''' + convert(varchar,star) + '''', ',null') + ' magstar' + convert(varchar,magtype) + char(10) + isnull(',''' + convert(varchar,logdate) + ''' logtype', '') + isnull(convert(varchar,logtype), '') + char(10) res xml path('')) ,1,1,''); exec sp_executesql @sql;
Comments
Post a Comment