How can I iterate over a recordset within a stored procedure?

后端 未结 3 655
醉梦人生
醉梦人生 2021-02-02 12:33

I need to iterate over a recordset from a stored procedure and execute another stored procedure using each fields as arguments. I can\'t complete this iteration in the code. I h

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 13:02

    Well its very easy to loop through the rows in sql procedure u just need to use cursor, i am giving you an example here, for it let us consider a table Employee with column NAME and AGE with 50 records into it and u have to execute a stored procedure say TESTPROC which will take name and age parameters of each row.

    create procedure CursorProc
    as
    begin
       declare @count bigint;
       declare @age varchar(500)
       declare @name varchar(500)
       select @count = (select count(*) from employee)
       declare FirstCursor cursor for select name, age from employee
       open FirstCursor 
       while @count > 0
          begin
             fetch FirstCursor into @name, @age
             Exec TestProc @name, @age
             set @count = @count - 1
          end
       close FirstCursor 
       deallocate FirstCursor 
    end
    

    Make sure you deallocate the cursor to avoid errors.

提交回复
热议问题