Reputation: 660
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.
Upvotes: 26
Views: 61801
Reputation: 754468
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
:
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:
WITH cOldest AS
(
.....
)
SELECT c.*
INTO #MyTempTable
FROM cOldest c
WHERE C.rnDOB = 1
Upvotes: 47