The problem that I need to resolve is data transfer from one table with many dynamic fields into other structured key value table. The first table comes from a data export from another system, and has the following structure ( it can have any column name and data): [UserID],[FirstName],[LastName],[Email],[How was your day],[Would you like to receive weekly newsletter],[Confirm that you are 18+] ...
The second table is where I want to put the data, and it has the following structure: [UserID uniqueidentifier],[QuestionText nvarchar(500)],[Question Answer nvarchar(max)]
I saw many examples showing how to unpivot table, but my problem is that I dont know what columns the Table 1 will have. Can I somehow dynamically unpivot the first table,so no matter what columns it has, it is converted into a key-value structure and import the data into the second table.
I will really appreciate your help with this.
You can't pivot or unpivot in one query without knowing the columns.
What you can do, assuming you have privileges, is query
sys.columns
to get the field names of your source table then build an unpivot query dynamically.In case you're getting your source data from a stored procedure, you can use
OPENROWSET
to get the data into a table, then examine that table's column names. This link shows how to do that part. https://stackoverflow.com/a/1228165/300242Final note: If you use a temporary table, remember that you get the column names from
tempdb.sys.columns
like so: