Can I create dynamic pivot query from key value ta

2019-07-21 16:40发布

问题:

I have a key-value pairs table. I have created a script using dynamic sql that pivots the table correctly. However, the keys have different data types. Is there a way to cast the keys during or after the pivot dynamically? I can have the data types in the same key-value pairs table for each key or in a separate table linkable by the key.

Dynamic sql is used because I wont always know the columns. There will always be a data type.

An example of the starting table:

sampleid     key   value    datatype
------------------------------------
1001        Name   Andrew    varchar(50)
1001        Date   20150129  datetime
1002        Name   Anna      varchar(50)
1002        Date   20150129  datetime

Final result would be this with name as nvarchar and date as datetime: The script is a stored procedure that creates this into a view. The view is being accessed via external applications like SAS and Olive which pick up the datatype from the view. Of course this isn't ideal but it is what I have been tasked with attempting!

sampleid  name      date
-----------------------------
1001     Andrew    20150129
1002     Anna      20150129

回答1:

You can do this using dynamic SQL, you'll just have to crate two separate lists of "new columns" as a string. One list will include the column names being converted to your datatype, the second will be used for the PIVOT function.

The code would be:

DECLARE 
    @cols AS NVARCHAR(MAX),
    @colsConversion AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

-- get the list of [key] items for the columns used in the PIVOT
select @cols 
  = STUFF((SELECT ', ' + QUOTENAME([key])
            from yourtable
            group by [key], datatype           
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

-- get the list of columns for the final select
-- include a conversion of the columns into the correct datatype
select @colsConversion 
  = STUFF((SELECT ', cast(' + QUOTENAME([key]) +' as '+ datatype+') as ' + QUOTENAME([key])
            from yourtable
            group by [key], datatype           
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

-- the converted columns go in the final select list 
-- while the other @cols are used inside the PIVOT
set @query = 'SELECT sampleid, ' + @colsConversion + ' 
            from 
            (
              select sampleid, [key], value
              from yourtable
            ) x
            pivot 
            (
               max(value)
               for [key] in (' + @cols + ')
            ) p; '

exec sp_executesql @query;

See SQL Fiddle with Demo