如何将cte的结果插入表变量
这样的东西?
DECLARE
@myData TABLE(
Title nvarchar(350) NOT NULL ,
Id int NOT NULL ,
);
INSERT INTO @myData
with CTE as
(SELECT
a.Title
,a.Id
FROM
TableA
)
,CTE2 as
(SELECT
b.Title
,b.Id
FROM
TableB
)
Select * From CTE
union all
Select * From CTE2
Select ROW_NUMBER() OVER(ORDER BY GetDate() DESC) AS RowId
, x.*
From @myData x
order by x.Id desc
答案 0 :(得分:10)
试试这个
with CTE as
(SELECT
a.Title
,a.Id
FROM
TableA
)
,CTE2 as
(SELECT
b.Title
,b.Id
FROM
TableB
)
INSERT INTO @myData --- insert statement goes here after CTE
Select * From CTE
union all
Select * From CTE2
Select ROW_NUMBER() OVER(ORDER BY GetDate() DESC) AS RowId, x.*
From @myData x
order by x.Id desc
答案 1 :(得分:0)
在我的SQL2019版本中,以上构造不插入任何字段。更糟糕的是,如果我想在语句后使用UPDATE,则会出现语法错误。
相反,此构造还可以在存储过程中工作:
; WITH CTE AS (
select ...
UNION ALL
select ...
)
insert into @tableVariable(fields..) (select field... from CTE)
希望有人会使用它。