使用WITH查询执行INSERT INTO

时间:2015-03-11 09:02:07

标签: sql sql-server sql-server-2012

我在此SO解决方案here中找到了一个查询,并希望在我正在处理的一个查询中使用它。解决方案中的示例查询如下:

;with t1 as (
    select col1, row_number() over (order by col1) rn
    from table1 
),
t2 as (
    select col2, row_number() over (order by col2) rn
    from table2
)
select col1,col2
from t1 full outer join t2 on t1.rn = t2.rn

而不是多次运行此查询(因为我需要在多个地方使用上述查询的结果),我想做类似下面的事情:

declare @tempTbl table (col1 int, col2 int)

insert into @tempTbl (col1, col2)
;with t1 as (
    select col1, row_number() over (order by col1) rn
    from table1 
),
t2 as (
    select col2, row_number() over (order by col2) rn
    from table2
)
select col1,col2
from t1 full outer join t2 on t1.rn = t2.rn

;with造成了麻烦...帮助Plz ......

1 个答案:

答案 0 :(得分:4)

公用表表达式在>插入之前

; with  t1 as 
        (
        ...
        )
,       t2 as 
        (
        ...
        )
insert  @tempTbl
        (col1, col2)
select  col1
,       col2
from    t1
full join
        t2
on      t1.rn = t2.rn
;