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.
You cannot create and drop the #TEMP table within the CTE query.
You can also use CTE to insert data into the SQL table. The CTE query definition includes the required data that you can fetch from existing tables using joins.
This biggest difference is that a CTE can only be used in the current query scope whereas a temporary table or table variable can exist for the entire duration of the session allowing you to perform many different DML operations against them.
A Common Table Expression, also called as CTE in short form, is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. The CTE can also be used in a View. In this article, we will see in detail about how to create and use CTEs from our SQL Server.
A Common Table Expression, also called as CTE in short form, is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. The CTE can also be used in a View. In this article, we will see in detail about how to create and use CTEs from our SQL Server. Syntax and Examples for Common Table Expressions
The CTE query starts with a “With” and is followed by the Expression Name. We will be using this expression name in our select query to display the result of our CTE Query and be writing our CTE query definition.
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: 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With