如何将查询的 CTE 输出保存到临时 table 或 table 变量中

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

我有一个CTE,查询这个

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

现在我尝试将此结果保存到 table variabletemporary table 中。如果我尝试

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

我在 WITH 语句周围得到一个 incorrect syntax error。我想 Insert Into 命令需要 Select statement 而不是 ;WITHCreate Table 也是如此。我一直在寻找解决方案,但所有 I found 都没有涉及 ;With 之后的 Select Statement。如何将上面显示的输出转换为 temporary tabletable variable

我使用 SQL Server 2014。

在 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;
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