如何在SQL Server中将动态数据透视表输出结果插入到临时表中?

时间:2019-04-01 08:54:15

标签: sql-server tsql pivot-table

我尝试了以下所有链接,但是它们在我的Sever SQL中不起作用吗?

SET @cols = STUFF((SELECT ',' + QUOTENAME(AD.MonthFormat) FROM #tempMonthFormat AD FOR xml PATH (''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
  SELECT @Selectcols =  STUFF((SELECT 
    ',' + ISNULL(@Selectcols + ',','')+ 'ISNULL(' + QUOTENAME(AD.MonthFormat) + ', 0) AS ' + QUOTENAME(AD.MonthFormat)  FROM #tempMonthFormat AD 
  FOR xml PATH (''), TYPE)
  .value('.', 'nvarchar(max)'), 1, 1, '');

Declare @FINALQUERY varchar(max);    
SET @FINALQUERY = '         
                      SELECT  Name,[Issue],' + @Selectcols + ' FROM
                     (
                         SELECT   into #temptable * FROM #Meantimeresult  
                     ) Y
                     PIVOT 
                     (
                         SUM(MT)
                         FOR [Monthformat] IN (' + @cols + ')               
                    ) p GROUP BY ' + @cols+',[Issue], Name'                

        EXEC SP_EXECUTESQL @FINALQUERY;

Dynamic SQL Result INTO #Temp Table

How to create temp table from a dynamic query?

INSERT INTO temp table from unknown number and name of columns (from dynamic PIVOT query) Dynamic Pivot Results to a Temp Table

1 个答案:

答案 0 :(得分:0)

可以通过几个步骤来完成,但是此答案的复杂特性应向您表明您在此处与sql server作战,而不是与之作战。尽力寻找另一种方式来组织报告,以免在采取此类严厉措施之前不需要这样做。

1)封装/修改您的初始数据透视查询为无参数存储过程。如果您需要将任何数据传递到过程中,则必须 将其构造为 global 临时表(以##为前缀的临时表),例如

CREATE PROCEDURE dynamic_meantime_pivot AS
DECLARE 
    @cols nvarchar(max) = STUFF(
        (SELECT ',' + QUOTENAME(AD.MonthFormat) FROM ##tempMonthFormat AD FOR xml PATH (''), TYPE)
        .value('.', 'nvarchar(max)'), 1, 1, '')
    @Selectcols nvarchar(max) = STUFF(
        (SELECT ',' + ISNULL(@Selectcols + ',','')+ 'ISNULL(' + QUOTENAME(AD.MonthFormat) + ', 0) AS ' + QUOTENAME(AD.MonthFormat)  FROM ##tempMonthFormat AD FOR xml PATH (''), TYPE)
        .value('.', 'nvarchar(max)'), 1, 1, '');

Declare @FINALQUERY varchar(max) = '         
                      SELECT  Name,[Issue],' + @Selectcols + ' FROM
                     (
                         SELECT * FROM ##Meantimeresult  
                     ) Y
                     PIVOT 
                     (
                         SUM(MT)
                         FOR [Monthformat] IN (' + @cols + ')               
                    ) p GROUP BY ' + @cols+',[Issue], Name'                

EXEC(@FINALQUERY)

2)设置上述过程所需的任何全局临时表。

3)通过OPENROWSET函数调用该过程,如下所示:

SELECT * INTO #dynamic_meantime_table FROM OPENROWSET('SQLNCLI', 'Server=<your_sql_server_instance_name_here>;Trusted_Connection=yes;',
     'EXEC dynamic_meantime_pivot')

另请参阅有关OPENROWSET的出色答案。

Insert results of a stored procedure into a temporary table