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