Unpivot ALL Columns in a SQL Table

后端 未结 1 1231
余生分开走
余生分开走 2021-01-06 12:48

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         


        
相关标签:
1条回答
  • 2021-01-06 13:16

    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.

    0 讨论(0)
提交回复
热议问题