2016-03-03 77 views
1

我有了這個動態創建的混亂,基本上是發生在一個表中的所有領域,並比較了兩種記錄彼此的工作:SELECT INTO #TEMP不與PIVOT

DECLARE @ID1 AS VarChar(3) 
DECLARE @ID2 AS VarChar(3) 

Set @ID1 = '42' 
Set @ID2 = '600' 

-- Where clause params 
DECLARE @whereClauseParam VARCHAR(MAX) = '['[email protected]+'] <> ['[email protected]+']' 

--***************************************-- 
--******** tblSQLAdminInventory ********-- 
--***************************************-- 
--Get the Fields required for the initial pivot 
DECLARE @AIFields VARCHAR(MAX)= ''; 
DECLARE @AIFields2 VARCHAR(MAX)= ''; 

SELECT @AIFields+=QUOTENAME(t.name)+', ' 
FROM sys.columns AS t 
WHERE t.object_id = OBJECT_ID('tblSQLAdminInventory') 
    AND t.name <> 'TransID' 
    --AND t.system_type_id = '56'; 

SELECT @AIFields2+='Convert(VarChar(250), '+QUOTENAME(t.name)+') AS '+ QUOTENAME(t.name) +', ' 
FROM sys.columns AS t 
WHERE t.object_id = OBJECT_ID('tblSQLAdminInventory') 
    AND t.name <> 'TransID' 
    --AND t.system_type_id = '56'; 
--56 (Int) 
--61 (DateTime) 
--104 (Bit) 
--167 (VarChar) 
--231 (NVarChar) 

-- Get the KeyId's with alias added 
DECLARE @AIkeyIDs VARCHAR(MAX),  
     @AIkeyIDs1 VARCHAR(MAX); 

SELECT @AIkeyIDs = COALESCE(@AIkeyIDs + ',','') + QUOTENAME(t.TransID) + ' AS [KeyID_' + CAST(t.TransID AS VARCHAR(10)) + ']', 
     @AIkeyIDs1 = COALESCE(@AIkeyIDs1 + ',','') + QUOTENAME(t.TransID) 
FROM tblSQLAdminInventory AS t 
WHERE TransID IN (@ID1, @ID2); 

--Generate Dynamic SQL 
DECLARE @AISQL2 VARCHAR(MAX)= 'SELECT Value AS FieldName, '; 

SELECT @[email protected]+' 
FROM 
(SELECT TransID, Value, FieldName 
FROM 
    (SELECT TransID, '+SUBSTRING(@AIFields2, 1, LEN(@AIFields2)-1)+' 
    FROM tblSQLAdminInventory) p 
UNPIVOT 
    (FieldName FOR Value IN 
     ('+SUBSTRING(@AIFields, 1, LEN(@AIFields)-1)+') 
)AS unpvt) AS SourceTable 
PIVOT 
(
MAX(FieldName) 
FOR TransID IN ('[email protected]+') 
) AS PivotTable 
WHERE '[email protected] 

EXECUTE(@AISQL2); 

的問題是,它贏得了」 t似乎讓我把結果放在臨時表中。我嘗試過使用此代碼,但它一直告訴我#Temp1對象不存在:

SELECT @[email protected]+' 
    INTO #Temp1 
FROM 
(SELECT TransID, Value, FieldName 
FROM 
    (SELECT TransID, '+SUBSTRING(@AIFields2, 1, LEN(@AIFields2)-1)+' 
    FROM tblSQLAdminInventory) p 
UNPIVOT 
    (FieldName FOR Value IN 
     ('+SUBSTRING(@AIFields, 1, LEN(@AIFields)-1)+') 
)AS unpvt) AS SourceTable 
PIVOT 
(
MAX(FieldName) 
FOR TransID IN ('[email protected]+') 
) AS PivotTable 
WHERE '[email protected] 

我在做什麼錯?

回答

2

您正在使用動態SQL。 EXECUTE語句啓動一個全新的作用域,並且該臨時表在該作用域中不可用。

有幾種解決方法,比如使用一個永久性表格清除或使用全局臨時表格,但它們都有自己的陷阱。

+0

是否可以使用動態名稱創建全局臨時表?說,「## Temp」帶有當前時間戳的後綴? –

+0

我想說試一試,看看會發生什麼。 –

+1

得到它的工作。謝謝! –