我有CTE
并查询此内容
;With CTE_Table as (SELECT ...)
Select * from CTE_Table
现在我尝试将此结果保存到table variable
或temporary table
。如果我试试
Declare @Table table
(...)
INSERT INTO @Table (...)
HER I PUT THE CODE ABOVE
我在incorrect syntax error
声明周围得到WITH
。我想Insert Into
命令需要Select statement
而不是;WITH
,而Create Table
则相同。我一直在寻找解决方案,但所有I found都不涉及Select Statement
之后的;With
。如何将上面显示的输出变为temporary table
或table variable
?
我使用的是SQL Server 2014。
答案 0 :(得分:9)
在CTE声明之后立即将insert语句添加到主查询。
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;
答案 1 :(得分:0)
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