2015-03-03 93 views
5

我想把這個查詢的結果存儲到一個臨時表:插入的與CTE查詢結果到一個臨時表

WITH cOldest AS 
(
    SELECT 
     *, 
     ROW_NUMBER() OVER (PARTITION BY [MyKey] ORDER BY SomeColumn DESC) AS rnDOB 
    FROM MyTable 
) 
SELECT 
    C.* 
*** Insert into #MyTempTable *** This part doesn't work 
    FROM 
    cOldest C 
    WHERE 
    C.rnDOB = 1 

在此先感謝。

回答

4

假設這是SQL服務器:熱膨脹係數是好的只有一個聲明 - 所以你不能同時擁有SELECTINSERT - 只使用INSERT

WITH cOldest AS 
(
    SELECT 
     *, 
     ROW_NUMBER() OVER (PARTITION BY [MyKey] ORDER BY SomeColumn DESC) AS rnDOB 
    FROM MyTable 
) 
INSERT INTO #MyTempTable(Col1, Col2, ....., ColN) 
    SELECT Col1, Col2, ...., ColN 
    FROM cOldest C 
    WHERE C.rnDOB = 1 

這就要求#MyTempTable已經存在。如果要用SELECT創建它 - 請使用以下語法:

WITH cOldest AS 
(
..... 
) 
SELECT c.* 
INTO #MyTempTable 
FROM cOldest c 
WHERE C.rnDOB = 1 
+0

感謝馬克!我意識到爲了能夠導出臨時表,它必須是全局臨時表。進入## MyTempTable @marc_s – Ariox66 2015-03-06 07:53:36