SQL Server 2008 pivoting table with unknown column name -


i having trouble pivot following

    firstname    lastname     ----------------------     talyor       swift     bruno        mars 

to following

    columnname    columnvalue     --------------------------     firstname     talyor     lastname      swift     firstname     bruno     lastname      mars 

i don't have clue how start without hardcoding way retrieve column name system.

**column name in source table not given

here "dynamic" approach accomplished via xml.

clearly unpivot more performant

example

select c.*       ,columnorder = d.ordinal_position   yourtable  cross apply (select xmldata = cast((select a.* xml raw) xml) ) b  cross apply (                 select item   = attr.value('local-name(.)','varchar(100)')                       ,value  = attr.value('.','varchar(max)')                    b.xmldata.nodes('/row') n(r)                  cross apply n.r.nodes('./@*') b(attr)              ) c  join information_schema.columns d on d.table_name='yourtable' , d.column_name=c.item 

returns

item        value   columnorder firstname   talyor  1 lastname    swift   2 firstname   bruno   1 lastname    mars    2 

edit - dynamic unpivot

declare @sql varchar(max) =' select columnorder = d.ordinal_position       ,item       ,value   yourtable  unpivot (value item in ('+stuff((select ',' +quotename(name)                                          sys.columns                                         object_id = object_id('yourtable')                                         xml path ('')),1,1,'')                              +')) unpiv  join information_schema.columns d on d.table_name=''yourtable'' , d.column_name=unpiv.item ' --print @sql exec(@sql) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -