Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 have found samples on the internets, but they all seem to deal with a counter. I'm not sure if my problem involved a counter. I need the T-SQL equivalent of a foreach

Currently, my first stored procedure stores its recordset in a temp table, #mytemp. I assume I will call the secondary stored procedure like this:

while (something)     execute nameofstoredprocedure arg1, arg2, arg3 end 
like image 842
David Fox Avatar asked Apr 12 '10 13:04

David Fox


People also ask

Can we use looping in stored procedure?

The LOOP statement allows you to execute one or more statements repeatedly. The LOOP can have optional labels at the beginning and end of the block. The LOOP executes the statement_list repeatedly. The statement_list may have one or more statements, each terminated by a semicolon (;) statement delimiter.

Can we use for loop in stored procedure in SQL Server?

SQL Server does not support the For loop. Instead, you can use the WHILE Loop to implement the same functionality. This whole article is about the While loop in SQL Server.


1 Answers

You need to create a cursor to loop through the record set.

Example Table:

CREATE TABLE Customers (     CustomerId INT NOT NULL PRIMARY KEY IDENTITY(1,1)     ,FirstName Varchar(50)      ,LastName VARCHAR(40) )  INSERT INTO Customers VALUES('jane', 'doe') INSERT INTO Customers VALUES('bob', 'smith') 

Cursor:

DECLARE @CustomerId INT, @FirstName VARCHAR(30), @LastName VARCHAR(50)  DECLARE @MessageOutput VARCHAR(100)  DECLARE Customer_Cursor CURSOR FOR      SELECT CustomerId, FirstName, LastName FROM Customers   OPEN Customer_Cursor   FETCH NEXT FROM Customer_Cursor INTO     @CustomerId, @FirstName, @LastName  WHILE @@FETCH_STATUS = 0 BEGIN     SET @MessageOutput = @FirstName + ' ' + @LastName        RAISERROR(@MessageOutput,0,1) WITH NOWAIT      FETCH NEXT FROM Customer_Cursor INTO     @CustomerId, @FirstName, @LastName END CLOSE Customer_Cursor DEALLOCATE Customer_Cursor 

Here is a link to MSDN on how to create them.

http://msdn.microsoft.com/en-us/library/ms180169.aspx

This is why I used Raise Error instead of PRINT for output.
http://structuredsight.com/2014/11/24/wait-wait-dont-tell-me-on-second-thought/

like image 143
kemiller2002 Avatar answered Oct 22 '22 00:10

kemiller2002