0

可能重复:
如何从动态数据透视表中分配普通表?

我有这个查询:

DECLARE @Col NVARCHAR(MAX) = 
    (   SELECT  ', ' + QUOTENAME(CONVERT(VARCHAR, DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - (12 - Number), 0), 103)) + ' = [' + CAST(number AS VARCHAR) + ']'
        FROM    Master..spt_values
        WHERE   Type = 'P'
        AND     number BETWEEN 0 AND 12
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')



DECLARE @SQL NVARCHAR(MAX) = 
        N'WITH Data AS
        (   SELECT  DACP_Id, DACP_Value, ResultCenters.RSL_CodDescr AS CentroResultado, Users.USR_EmpName Colaborador, Devices.DEV_NoArea+Devices.DEV_No as AreaNumero,
                    [MonthNum] = 12 - DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP)
            FROM    DevicesAccompaniments INNER JOIN
                    Devices ON Devices.DEV_Id = DevicesAccompaniments.FK_DEV_Id INNER JOIN
                    ResultCenters ON ResultCenters.RSL_Id = Devices.DEV_RsltId INNER JOIN
                    Contracts ON Contracts.CNT_Id = Devices.DEV_ContrId INNER JOIN
                    Users ON Users.USR_Id = Devices.DEV_UsrId
            WHERE   DATEDIFF(MONTH, DACP_Date, CURRENT_TIMESTAMP) BETWEEN 0 AND 12 
        )   
        SELECT  CentroResultado, Colaborador, AreaNumero' + @Col + '
        FROM    Data
                PIVOT
                (   SUM(DACP_Value)
                    FOR MonthNum IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
                ) pvt;'

它创建了 12 列和关于我们当前日期过去 12 个月的附加信息,问题是我需要将此查询放入报告中,但我需要将列映射到带有 var @SQL 中的信息的临时表中,而不仅仅是执行'EXEC sp_executesql @SQL;' 这是从当前日期起过去 12 个月的示例小提琴:http ://www.sqlfiddle.com/#!3/3205a/14

欢迎任何帮助,谢谢。

4

1 回答 1

1

我有一个保存的脚本,它根据当前模式生成一个插入语句(使其适应我们数据库的未来版本)。这方面的基本思想是它合并来自一个表的数据(具有完全不同的模式,但我知道有相关数据)并使用目标表中的现有记录作为模板来填充缺失的数据。

我相信这个脚本比你需要的要复杂一些。但是,我认为您需要的所有工具都可以根据您的需要进行定制。

DECLARE @SourceID VARCHAR(50), @DestinationID VARCHAR(50), @TemplateID VARCHAR(50)
-- Replace with Source ID which has menus to convert
SELECT @SourceID = '<SCREENID>' 
-- Replace with Destination container ID which will contain the parent record for the new data.
SELECT @DestinationID = '<DestinationID >' 
-- ID of template record will will be used to fill in gaps in data.
SELECT @TemplateID = '<Template Record's ID>'

-- Initialize Cursor to gather schema about destination table.
---- This should make this script schema independent
DECLARE @ColumnBuilder NVARCHAR(4000),@ColumnTemp VARCHAR(50)
select @ColumnBuilder = ''

DECLARE ColumnCursor CURSOR LOCAL
FOR select Column_Name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<DESTINATION TABLE NAME>' ORDER BY ORDINAL_POSITION

OPEN ColumnCursor

FETCH NEXT FROM ColumnCursor
INTO @ColumnTemp

WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @ColumnBuilder = @ColumnBuilder + 'C.' + @ColumnTemp + ','

FETCH NEXT FROM ColumnCursor
INTO @ColumnTemp

END
CLOSE ColumnCursor
DEALLOCATE ColumnCursor
-- End Cursor

-- Modify some values, for example, we don't want to copy in the template's PK, instead we'll generate a newid()
SELECT @ColumnBuilder = SUBSTRING(@ColumnBuilder, 1,LEN(@ColumnBuilder)-1) -- get rid of last comma.

SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.TableID,','newid(),')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.ParentID,','''' + @DestinationID + ''',')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.ColumnINeverWantCopied,','NULL,')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.TranslateMe,','MI.TranslateableData,')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.Order,','MI.Order + C.Order,')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.EntryBy,','''TranslateScript'',')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.UpdateBy,','''TranslateScript'',')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.EntryDtm,','getdate(),')
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.UpdateDtm,','getdate(),')

-- Set Label of new buttons
SELECT @ColumnBuilder = REPLACE(@ColumnBuilder,'C.Label,','
CASE WHEN MI.Alias IS NULL
THEN
CASE WHEN MI.CommandID = 7 THEN ''Dial''
WHEN MI.CommandID = 8 THEN ''Email''
ELSE S.Alias
END
ELSE MI.AlternateAlias
END,')

-- Build INSERT statement
SELECT @ColumnBuilder = 'INSERT INTO <Destination table> SELECT ' + @ColumnBuilder + ' from 
(<Source Table> MI LEFT JOIN <Source's Parent Table> S ON MI.ParentID = S.ParentID), <Destination table> C
WHERE MI.ParentID= ''' + @SourceID  + ''' AND C.TableID = ''' + @TemplateID  + ''' 
AND MI.CommandID NOT IN (25,43,32,11,45)'

-- Return whole generated statement, for debugging
SELECT @ColumnBuilder

-- Execute!
exec sp_executesql @ColumnBuilder
于 2013-02-04T16:36:30.313 回答