【发布时间】:2018-05-03 14:07:34
【问题描述】:
我有这种情况:
drop table #t1;
drop table #t2
select *
into #t1
from
(select 'va1'c1,'vb1'c2,'vc1'c3 union all
select 'va2'c1,'vb2'c2,'vc2'c3 union all
select 'va3'c1,'vb3'c2,'vc3'c3 union all
select 'va1'c1,'vb1'c2,'vc1'c3 union all
select 'va2'c1,'vb2'c2,'vc2'c3 union all
select 'va3'c1,'vb3'c2,'vc3'c3 union all
select 'va1'c1,'vb1'c2,'vc1'c3 union all
select 'va2'c1,'vb2'c2,'vc2'c3 union all
select 'va3'c1,'vb3'c2,'vc3'c3 union all
select 'va1'c1,'vb1'c2,'vc1'c3 union all
select 'va2'c1,'vb2'c2,'vc2'c3 union all
select 'va3'c1,'vb3'c2,'vc3'c3 union all
select 'va4'c1,'vb4'c2,'vc4'c3) t
select *
into #t2
from #t1
where 0 = 1
;with tmp1 as
(
select
t1.*,
ROW_NUMBER() over (partition by t1.c1 order by (select null)) r
from
#t1 t1
left join
#t2 t2 on t1.c1 = t2.c1
where
t2.c1 is null
), tmp2 as
(
select
0 n,*
from
tmp1
union all
select
n+1 n, t1.c1, t1.c2, t1.c3, t1.r
from
tmp2 t1
join
tmp1 t2 on t1.c1 = t2.c1
and t2.r = t1.r + 1
where
n < 10
)
--insert #t2
select c1, c2, c3 --,r
from tmp2
当我运行它时,它会选择一切正常(103 条记录)。
问题是当我将这段代码插入#t2(13条记录!!!)
我认为 SQL 是一步一步运行的,并且在运行过程中插入记录,而我在 tmp1 中的条件已经结束...
如何解决?
我的目标是检查数据是否存在,然后循环并插入结果...但是 SQL 在第一个循环后停止...
【问题讨论】:
-
我相信这对你来说很清楚,但对于我们这些不熟悉你所做的事情的人来说,这没有多大意义。
-
如果您运行提供的查询,您将看到最终选择返回 103 条记录,如果插入未注释,则插入 13 条记录。我认为这就是问题所在。
-
如果将其与 insert 一起使用,SQL 会忽略递归 CTE。
-
我建议将此作为错误报告给 Microsoft。与此同时,@lad2025 的解决方法就像做一个
SELECT INTO第三个临时表然后使用它插入到你的#t2 -
你确定这是一个错误吗??以防万一,我该如何举报?
标签: sql sql-server tsql common-table-expression recursive-cte