How to save a queried CTE output into a temporary table or table variable

ruedi picture ruedi · Sep 2, 2015 · Viewed 9.5k times · Source

I have a CTE and query this one

;With CTE_Table as (SELECT ...)
Select * from CTE_Table

Now I try to save this result into a table variable or temporary table. If I try

Declare @Table table
(...)
INSERT INTO @Table (...)
HER I PUT THE CODE ABOVE

I get an incorrect syntax error around the WITH statement. I guess the Insert Into command expects a Select statement instead of a ;WITH and the same goes for Create Table. I was looking for solutions but all I found did not involve the Select Statement after the ;With. How do I get the output shown above into a temporary table or table variable?

I use SQL Server 2014.

Answer

Mikael Eriksson picture Mikael Eriksson · Sep 2, 2015

You add the insert statement to the main query right after the CTE declarations.

declare @T table(ID int);

with C(ID) as
(
  select 1 union all
  select 2
)
insert into @T(ID)
select ID
from C;

select ID
from @T;