5

如何让结果WITH table AS进入CURSOR循环?我之前曾问过如何从我的表中获取递归结果

如何递归读取所有记录并按级别深度TSQL显示

;with C as
(
    definition ...
)

我创建了 CURSOR 循环,我想在其中为所有结果运行特定的存储过程table

declare @id int, @parent int
declare cur cursor local fast_forward 
for 
    select id, parent from C
open cur
fetch next from cur into @id, @parent
while @@fetch_status = 0
    begin
    exec storedProcedure @id=@id, @parent=@parent
fetch next from cur into @id, @parent
end
close cur
deallocate cur

问题是 CURSOR 不知道tableWITH AS 结果。

Invalid object name 'C'.
4

1 回答 1

3

您可以创建一个临时表或表变量来保存 CTE 查询返回的行,然后将该表用作游标的源。

declare @T table
(
  id int,
  parent int
)

;with C as
(
  select 1 as id, 2 as parent
)
insert into @T
select id, parent
from C

declare cur cursor for select id, parent from @T
于 2012-04-25T08:27:27.140 回答