插入临时表动态数据透视表

时间:2015-11-12 06:51:53

标签: sql sql-server tsql sql-server-2008-r2

我有以下t-sql:

select      d.OutageType + '/' + e.Facility Outage,
            c.MaterialScopeCode, 
            count(a.ItemNo) CountofItemNo
into        #tt
from        _OutageMaterial a
            inner join _OutageSchedule b on a.OutageScheduleID = b.OutageScheduleID
            inner join _MaterialScope c on a.MaterialScopeID = c.MaterialScopeID
            inner join _OutageType d on b.OutageTypeID = d.OutageTypeID
            inner join _Facility e on b.FacilityID = e.FacilityID
where       ReqQty <> 0
group by    c.MaterialScopeCode, e.Facility, d.OutageType
order by    d.outagetype, e.Facility, c.MaterialScopeCode


-- /// RESULT /// --
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT      @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(Outage)
FROM        (
            SELECT DISTINCT         Outage 
            FROM                    #tt
            ) AS Scope

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT MaterialScopeCode as Scope, ' + @ColumnName + '
FROM #tt
PIVOT(SUM(CountofItemNo) 
FOR Outage IN (' + @ColumnName + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

我已经尝试了很多次,但仍然..错误。我无法选择临时表,因为它没有创建。无效的对象。我想将动态数据的结果放入临时表中 我怎样才能做到这一点?请指教。

谢谢。

2 个答案:

答案 0 :(得分:2)

@ MM93告诉你的是,这是正确的答案,但这里是完整的代码

IF OBJECT_ID('TEMPDB.dbo.##TempTableTesting') IS NOT NULL DROP TABLE ##TempTableTesting

declare @sql nvarchar(300) = 'SELECT MaterialScopeCode as Scope, ' + @ColumnName + '
into ##TempTableTesting
FROM #tt
PIVOT(SUM(CountofItemNo) 
FOR Outage IN (' + @ColumnName + ')) AS PVTTable'

execute sp_executesql @sql

select * from ##TempTableTesting

因此,在您的情况下,您必须使用## TempTable,因为这些表(全局)可用于所有会话,#TempTable在您的案例中无法工作

答案 1 :(得分:1)

我回答了这个问题here所以我不会复制,但简短的回答是可以将动态数据透视的结果插入到本地(非全局)临时表中,你只需要使用单个列创建临时表,然后动态添加其他列。