I have a table with 30 columns and I want to easily unpivot ALL columns. I understand I can use this strategy:
SELECT col, value
INTO New_Table
FROM
(SELECT
This seems like a broken data model, but you can avoid typing out lists of columns.
You can use this to generate a list of columns:
SELECT name
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
And:
DECLARE @List VARCHAR(MAX) = STUFF((SELECT DISTINCT ',' + QUOTENAME(name)
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
PRINT @List
You can then use that list in a dynamic sql statement:
DECLARE @List VARCHAR(MAX) = STUFF((SELECT DISTINCT ',' + QUOTENAME(name)
FROM sys.columns
WHERE objecT_id = OBJECT_ID('Test_Data')
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
,@sql VARCHAR(MAX)
SET @sql = 'SELECT col,value
INTO New_Table
FROM (SELECT * FROM Test_Data) p
UNPIVOT (value FOR col IN ('+@List+')) as unpvt
'
EXEC (@sql)
I suggest using PRINT (@sql)
before using EXEC
to ensure the dynamic query is what you were after.