我想在動態數據透視查詢中使用臨時表。我讀過該過程不起作用,因爲即使它是一個全局表,臨時表也不在該範圍之內。這對我來說很奇怪,因爲它在sql小提琴中有效,但在SQL Server 2012中不起作用。我如何編輯我的查詢以使它給出輸出,而不是(受xxx行影響)?在動態數據透視表中使用臨時表
這裏是我的查詢:
SELECT cc.CaseCaseId AS CaseId, cc.Label AS CaseName, rce.EcoDate, cc.OperatorName, cc.State, cc.County, ei.IROR, rce.NDCash
into ##Temp2
FROM PhdRpt.ReportCaseList_542 AS rcl INNER JOIN
CaseCases AS cc ON rcl.CaseCaseId = cc.CaseCaseId INNER JOIN
PhdRpt.RptCaseEco_542 AS rce ON rcl.ReportRunCaseId = rce.ReportRunCaseId INNER JOIN
PhdRpt.EcoIndicators_542 AS ei ON rcl.ReportRunCaseId = ei.ReportRunCaseId
DECLARE @colsPivot AS NVARCHAR(MAX),
@colsUnpivot as NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(EcoDate)
from ##Temp2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('##Temp2') and
C.name LIKE 'NDCash%'
for xml path('')), 1, 1, '')
set @query
= 'select *
from
(
select cc.CaseCaseId AS CaseId, cc.Label AS CaseName, rce.EcoDate, cc.OperatorName, cc.State, cc.County, ei.IROR, val, col
FROM ##Temp2
unpivot
(
val
for col in ('+ @colsunpivot +')
) u
) x1
pivot
(
max(val)
for EcoDate in ('+ @colspivot +')
) p'
exec(@query)
Drop table ##Temp2
這裏是表結構:
CaseId EcoDate NDCash
2 2003-01-01 26.6384943638238
2 2004-01-01 23.9534867373416
2 2005-01-01 25.9197356158675
2 2006-01-01 25.3280437702064
2 2007-01-01 24.9828609298022
2 2008-01-01 26.4019321789285
2 2009-01-01 26.6384943638238
2 2010-01-01 24.0660715481002
2 2011-01-01 26.6384943638238
2 2012-01-01 22.5718444448345
2 2013-01-01 26.6384943638238
與使用##全局臨時表時所用的更直接的問題是,這有效地限制併發至1.你認爲當兩個用戶運行此情況代碼在同一時間? –
@AaronBertrand你認爲什麼是解決方案?我是新來的SQL,所以任何建議表示讚賞。 –
我甚至沒有試圖消化你的問題。我只知道全局的## temp表很少是正確的解決方案。 –