Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 895
ruedi Avatar asked Dec 24 '22 14:12

ruedi


1 Answers

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;
like image 97
Mikael Eriksson Avatar answered Dec 27 '22 03:12

Mikael Eriksson