In SQL Server (T-SQL), you cannot write WITH cte AS (...) SELECT ... INTO #temp FROM cte; directly because a Common Table Expression (CTE) must be immediately followed by a single SELECT, INSERT, UPDATE, DELETE, or MERGE statement—not SELECT ... INTO. To create a local temporary table () from a CTE’s result set, either place the INTO #temp clause inside the CTE’s SELECT statement or insert the CTE’s output into a pre-created table using INSERT INTO #temp ... WITH cte AS (...) SELECT ....
1. Recommended: INSERT INTO #temp Paired with a CTE
Define the table (or create it on the fly) and run the CTE right after INSERT INTO #temp:
-- Option 1A: Create #temp explicitly, then populate via CTE
CREATE TABLE #high_value_orders (
customer_id INT NOT NULL,
order_count INT NOT NULL,
total_spent DECIMAL(18, 2) NOT NULL
);
WITH customer_summary AS (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM dbo.orders
WHERE status = 'COMPLETED'
GROUP BY customer_id
)
INSERT INTO #high_value_orders (customer_id, order_count, total_spent)
SELECT
customer_id,
order_count,
total_spent
FROM customer_summary
WHERE total_spent >= 1000.00;
SELECT *
FROM #high_value_orders
ORDER BY total_spent DESC;
DROP TABLE #high_value_orders;
- Explicit column definitions let you control exact data types,
NULLability, and primary/clustered indexes (PRIMARY KEY CLUSTERED) up front.
2. Placing INTO #temp Inside the CTE’s SELECT
SQL Server allows INTO #temp inside the SELECT query that defines a CTE (though it creates the temp table during CTE evaluation rather than acting as the outer statement after the CTE):
WITH ranked_orders AS (
SELECT
order_id,
customer_id,
total_amount,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY created_at DESC
) AS rn
INTO #latest_customer_orders
FROM dbo.orders
WHERE status = 'COMPLETED'
)
SELECT
order_id,
customer_id,
total_amount
FROM #latest_customer_orders
WHERE rn = 1;
DROP TABLE #latest_customer_orders;
- Because
SELECT ... INTOinfers column types from expressions, always wrap computed columns orNULLliterals inCAST()/CONVERT()/ISNULL()so unintended types orNULLcolumns do not cause surprises later.
3. Alternative Without a CTE: Derived Table + SELECT ... INTO
If you only need a one-step transformation and want SELECT ... INTO as the main statement, a derived table (subquery in FROM) works cleanly:
SELECT
sub.customer_id,
sub.order_count,
sub.total_spent
INTO #customer_spend
FROM (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM dbo.orders
WHERE status = 'COMPLETED'
GROUP BY customer_id
) AS sub
WHERE sub.total_spent >= 500.00;
Safe Execution Checklist in T-SQL
- Avoid
WITH cte (...) SELECT ... INTO #t FROM cte: SQL Server raises a syntax error (Incorrect syntax near the keyword 'into') whenINTOfollows a CTE reference. - Explicitly type expressions when using
INTO #temp: Cast aggregates or expressions (such asCAST(SUM(...) AS DECIMAL(18, 2))) to prevent truncation or overflow during laterUPDATEorINSERToperations. - Clean up or scope temp tables to the batch/session: Session-scoped
tables are automatically dropped when the session ends, and dropping them explicitly (IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp;) makes re-running scripts in the same session safe.
