[英]INSERT INTO Temp Table Dynamic Pivot
I've the following t-sql: 我有以下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
I've tried many times, but still .. Error. 我已经尝试了很多次,但是仍然..错误。 I could not select the temp table because it doesn't created. 我无法选择临时表,因为它没有创建。 Invalid Object. 无效的对象。 I want to put the result of dynamic pivot into temp table. 我想将动态数据透视的结果放入临时表中。
How can i do that? 我怎样才能做到这一点? Please advise. 请指教。
Thank you. 谢谢。
what @MM93 told you, that is correct answer, but here is full code @ 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
So in your case you have to use ##TempTable as those tables (global) are available to ALL sessions, #TempTable won't work in your case 因此,在您的情况下,您必须使用## TempTable,因为这些表(全局)可用于所有会话,而#TempTable在您的情况下将不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.