在各种情况下如何从CTE插入多个变量?

时间:2019-02-24 12:47:00

标签: sql-server sql-insert sql-cte

有一个表我使用with子句进行SQL查询。

正如标题中所述,我想在不同条件下从@tempTableA插入@tempTableBSomeTable中。

但是它不起作用。我对CTE有什么误解?还有其他方法可以实现吗?

declare @tempTableA table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))

declare @tempTableB table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))

; with SomeTable as (
    select
        FieldId
        , FieldName1
        , FieldName2
        , FieldName3
    from tableA
    cross apply tableB)

insert @tempTableA 
select * from SomeTable where FieldName1 > 10

insert @tempTableB
select * from SomeTable where FieldName1 <= 10

1 个答案:

答案 0 :(得分:3)

您只能在定义后加上一个查询来使用CTE(CTE范围和后续CTE仅用于单个查询),例如:

create table Table1 (
    pkTable1 int primary key
    , fkTable2 int
    , Column1 nvarchar(max)
)

create table Table2 (
    pkTable2 int primary key
    , fkTable3 int
    , Column2 nvarchar(max)
)

create table Table3 (
    pkTable3 int primary key
    , Column3 nvarchar(max)
)

; with cte1 as (
    select pkTable1, fkTable2, Column1
    from Table1
)
, cte2 as (
    select pkTable2, fkTable3, Column2
    from Table2
)
, cte3 as (
    select * from cte1
        join cte2 on cte1.fkTable2=cte2.pkTable2
)
select * from cte3
    join Table3 on cte3.fkTable3=Table3.pkTable3

(*:因为这只是一个演示,所以不用担心如何优化它,也不用担心查询没有任何意义。)

如果要在多个语句中使用它,请使用临时表table variable,或者需要为下一条语句再次定义CTE

例如,您可以使用如下临时表来实现相同目的。

declare @tempTableA table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))
declare @tempTableB table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))
select
    FieldId
    , FieldName1
    , FieldName2
    , FieldName3
    into #t3 --Assign to temp table
from tableA
cross apply tableB

insert into @tempTableA 
select * from  #t3 where FieldName1 > 10

insert @tempTableB
select * from  #t3 where FieldName1 <= 10

drop table #t3 --Drop the table

对于您的情况,您不需要CTE,可以像下面这样编写查询:

declare @tempTableA table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))
declare @tempTableB table (FieldId nvarchar(4000), FieldName1 nvarchar(4000), FieldName2 nvarchar(4000), FieldName3 nvarchar(4000))
insert into @tempTableA 
select
    FieldId
    , FieldName1
    , FieldName2
    , FieldName 
from tableA
cross apply tableB where FieldName1 > 10

insert @tempTableB
select
    FieldId
    , FieldName1
    , FieldName2
    , FieldName 
from tableA
cross apply tableB where FieldName1 <= 10