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

fer*_*vak 5 t-sql cursor with-statement

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

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

;with C as
(
    definition ...
)
Run Code Online (Sandbox Code Playgroud)

我创建了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
Run Code Online (Sandbox Code Playgroud)

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

Invalid object name 'C'.
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 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
Run Code Online (Sandbox Code Playgroud)