in

ASP.NET Weblogs

life in a smart mob

social networking and other stuff

Looping through a rowset to reuse a Stored Procedure

Ever written a stored procedure where you want to select from a table and then loop through each row returned and pass in values from each column in each row into a stored procedure.

Thanks to Andrew Kelly for his help in producing a working stored procedure as follows (fragment shown).

 DECLARE MYCURSOR CURSOR FOR
  (SELECT p1, p2
   FROM  tbl_MyTable
   WHERE p4=123)

 DECLARE @p1 INT
 DECLARE @p2 INT
 DECLARE @p3 INT

 OPEN MYCURSOR
  FETCH NEXT FROM MYCURSOR INTO @p1, @p2, @p3

  WHILE @@FETCH_STATUS = 0
   BEGIN

    -call stored procedure
    exec UpdateTable @p1, @p2, @p3

    FETCH NEXT FROM MYCURSOR

   END

    CLOSE MYCURSOR
    DEALLOCATE MYCURSOR

vtgo.net

Comments

 

Mike said:

I probably don't need to point this out, but you should also seriously consider adding functionality to the original stored procedure (like in optional parameters) to have it select a set of rows and perform the operations as a set rather than iteratively. Cursors are bad news for performance and scalability. And doing things iteratively in SQL is never as good as performing set-based operations.

Nevertheless, if you have no control on the inner stored proc, I would suggest using a table variable rather than a cursor. I'm going to blog such a technique this weekend and post a link back here if you're interested.
February 7, 2004 1:28 PM
 

Lance said:

Cursors = baaaaaad

Consult your local DBA for more details. :)
February 7, 2004 1:28 PM
 

Enigma said:

Set based operations are always faster than a cursor .. someone has yet to show me a place where a cursor performs better than a set based operation ...
February 7, 2004 3:19 PM
 

TrackBack said:

February 7, 2004 3:48 PM
 

Steven Livingstone said:

No to harp on, but any you guys got an alternative example? Say, not using cursors that does the exact same thing?
February 7, 2004 7:27 PM
 

TrackBack said:

March 5, 2004 5:36 AM

Leave a Comment

(required)  
(optional)
(required)  
Add