Search code examples
t-sqlwith-statementdatabase-cursor

How to use WITH table AS result within cursor loop to run stored procedure


How to get result in WITH table AS into CURSOR loop? I have previously asked about how to get recursive results from my table

How to read all records recursively and show by level depth TSQL

;with C as
(
    definition ...
)

I have created CURSOR loop where I want to run specific stored procedure for all results in 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

Problem is that CURSOR doesnt know table from WITH AS result.

Invalid object name 'C'.

Solution

  • You can create a temp table or a table variable to hold the rows returned by you CTE query and then you use that table as the source for your cursor.

    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