如何在游标循环中使用WITH表AS结果来运行存储过程

时间:2012-04-25 08:08:43

标签: tsql cursor with-statement

如何将WITH table AS的结果导入CURSOR循环?我之前已经问过如何从我的表中获取递归结果

How to read all records recursively and show by level depth 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从WITH AS结果中不知道table

Invalid object name 'C'.

1 个答案:

答案 0 :(得分: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