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

时间:2022-10-21 19:58:00

I want to store the result of this query into a temp table:

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

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

Thanks in advance.

提前致谢。

1 个解决方案

#1


8  

Assuming this is for SQL Server : the CTE is good for only one statement - so you cannot have both a SELECT and an INSERT - just use the INSERT:

假设这是针对SQL Server的:CTE仅适用于一个语句 - 因此您不能同时使用SELECT和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

This requires that the #MyTempTable already exists. If you want to create it with the SELECT - use this syntax:

这要求#MyTempTable已经存在。如果要使用SELECT创建它 - 请使用以下语法:

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

#1


8  

Assuming this is for SQL Server : the CTE is good for only one statement - so you cannot have both a SELECT and an INSERT - just use the INSERT:

假设这是针对SQL Server的:CTE仅适用于一个语句 - 因此您不能同时使用SELECT和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

This requires that the #MyTempTable already exists. If you want to create it with the SELECT - use this syntax:

这要求#MyTempTable已经存在。如果要使用SELECT创建它 - 请使用以下语法:

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