2015-11-12 75 views
0

我下面的T-SQL:INSERT INTO臨時表動態透視

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 

我試過很多次,但仍..錯誤。我無法選擇臨時表,因爲它沒有創建。無效的對象。我想將動態數據透視的結果放入臨時表中。
我該怎麼做?請指教。

謝謝。

+0

您是否嘗試在動態查詢中創建臨時表。如果是,那部分 –

+0

我想把動態數據透視的結果放到#temp表中,然後選擇它。在動態查詢'FROM #tt – Haminteu

+0

嘗試進入##臨時 PIVOT(SUM(CountofItemNo)'這個**注:**,這將拋出時,在多個會話 –

回答

1

什麼@ 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

我回答了這個here所以我不會重複,但簡短的答案是可以將動態數據透視的結果插入到本地(而非全局)臨時表中,您只需要使用單個列創建臨時表,然後動態添加其他列。