将带有cte查询的结果插入临时表

时间:2015-03-03 06:17:36

标签: sql-server common-table-expression

我想将此查询的结果存储到临时表中:

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

提前致谢。

1 个答案:

答案 0 :(得分:16)

假设这是针对 SQL Server :CTE仅适用于一个语句 - 因此您不能同时拥有SELECT和{{1} } - 只需使用INSERT

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