使用Unpivot和动态列创建新表

时间:2017-08-28 18:03:15

标签: sql-server dynamic unpivot

我一直在尝试使用动态列来移动大型数据库,同时保留两个索引列。我无法将其作为新表保存在SQL Server Management Studio中作为新表。现在我得到' INSERT语句不能包含为变量赋值的SELECT语句。'

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

create table pivot_columns ([Prime Item Nbr] NVARCHAR(MAX), [Store Nbr] NVARCHAR(MAX))


insert into pivot_columns

select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(column_name)
                      FROM information_schema.columns
                      WHERE table_name = 'POSSalesMicro'
                        AND COLUMN_NAME <> 'Prime Item Nbr' 
                        AND COLUMN_NAME <> 'Store Nbr'
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');




SELECT @query = 'WITH Unpivoted 
                AS
                (
                    SELECT [Prime Item Nbr], [Store Nbr], columns, value
                    FROM POSSalesMicro
                    UNPIVOT
                    (
                       columns
                       FOR value IN('+ @cols + ')
                    ) AS u
                ) 
                SELECT 
                  [Prime Item Nbr], 
                  [Store Nbr],
                  columns,
                  CAST(CASE WHEN value LIKE ''% POS Sales'' THEN REPLACE(value,''POS Sales'', '''')
                       WHEN value LIKE ''LR%'' THEN REPLACE(value,''LR '', '''')
                  END AS INT) AS WMWeek
                FROM Unpivoted';


EXECUTE(@query);

1 个答案:

答案 0 :(得分:1)

您需要制作动态sql的插入部分。这些方面的东西。

select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(column_name)
                      FROM information_schema.columns
                      WHERE table_name = 'POSSalesMicro'
                        AND COLUMN_NAME <> 'Prime Item Nbr' 
                        AND COLUMN_NAME <> 'Store Nbr'
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');

SELECT @query = 'WITH Unpivoted 
                AS
                (
                    SELECT [Prime Item Nbr], [Store Nbr], columns, value
                    FROM POSSalesMicro
                    UNPIVOT
                    (
                       columns
                       FOR value IN('+ @cols + ')
                    ) AS u
                ) 
                insert into pivot_columns (' + @cols + ') 
                SELECT 
                  [Prime Item Nbr], 
                  [Store Nbr],
                  columns,
                  CAST(CASE WHEN value LIKE ''% POS Sales'' THEN REPLACE(value,''POS Sales'', '''')
                       WHEN value LIKE ''LR%'' THEN REPLACE(value,''LR '', '''')
                  END AS INT) AS WMWeek
                FROM Unpivoted';

exec sp_executesql @query