How to save requested CTE output to a temporary table or table variable

I have a CTErequest for this

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

Now I am trying to save this result in table variableor temporary table. If i try

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

I get incorrect syntax erroraround the operator WITH. I assume that the team Insert Intoexpects Select statementinstead ;WITH, as well as for Create Table. I was looking for solutions, but everything I found did not turn on Select statementafter ;WITH. How to get the output shown above in temporary tableor table variable?

I am using SQL Server 2014.

+4
source share
2 answers

insert CTE.

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;
+8
DECLARE @t table(
Name nvarchar(MAX),
Id bigint
)

;WITH CTE as (
    SELECT 'Name' as Name , 1 as Id
)
INSERT INTO @t(Name,Id)
SELECT Name,Id FROM CTE


SELECT * FROM @t
0

All Articles