我下面的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
我試過很多次,但仍..錯誤。我無法選擇臨時表,因爲它沒有創建。無效的對象。我想將動態數據透視的結果放入臨時表中。
我該怎麼做?請指教。
謝謝。
您是否嘗試在動態查詢中創建臨時表。如果是,那部分 –
我想把動態數據透視的結果放到#temp表中,然後選擇它。在動態查詢'FROM #tt – Haminteu
嘗試進入##臨時 PIVOT(SUM(CountofItemNo)'這個**注:**,這將拋出時,在多個會話 –