sql server - How to pivot dynamic number of columns row result into a verticle result list -


there single row of data in table have varying number of columns named c1, c2, c3.. etc. can locate row want un-pivot dynamic number of columns values single column result... have researched ton on pivot/unpivot stuff examples i've found don't seem handle dynamic number of columns in results.

native results:

col 1 col 2 col 3 col 4 col 5.... col x

id name dob city state

desired results:

columnnametbd:

id name dob city state

thank you!

tim

after feedback question able piece solution. have way physically instanciate structure dynamic/inconsistent structure automatically.

    declare @scolumnnames varchar(5000)     declare @ssql   varchar(5000);      --flatten list of column names      select @scolumnnames = ' ' + (                  select '(' + column_name + '),' 'data()'                    smar_stg.information_schema.columns  (nolock)                   table_name = 'v_etl_ctx_corem_excel_dtl_columns'                    xml path('')             )  + ' '      --get rid or trailing comma     set @scolumnnames = substring(@output,1,len(@output) -1)       -- assemble sql statement     set @ssql = 'select upivot x                   smar_stg.dbo.v_etl_ctx_corem_excel_dtl_columns                        cross apply (values '     set @ssql = @ssql + @scolumnnames     set @ssql = @ssql + ') cs (upivot) '      -- execute     exec (@ssql) 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -