Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL loop over query results

Tags:

tsql

I run a query select @id=table.id from table and I need to loop over the results so I can exec a store procedure for each row exec stored_proc @varName=@id,@otherVarName='test'

How can I do this in a T-SQL script?

like image 777
Justin808 Avatar asked Aug 07 '12 19:08

Justin808


People also ask

How do you loop through a record in a table in SQL?

DECLARE @RowCnt int; SET @RowCnt = 0 -- Loop Counter. -- Use a table variable to hold numbered rows containg MyTable's ID values. DECLARE @tblLoop TABLE (RowNum int IDENTITY (1, 1) Primary key NOT NULL, ID INT )

Can we run SQL query in loop?

SQL WHILE loop provides us with the advantage to execute the SQL statement(s) repeatedly until the specified condition result turn out to be false. In the following sections of this article, we will use more flowcharts in order to explain the notions and examples.


1 Answers

You could use a CURSOR in this case:

DECLARE @id INT DECLARE @name NVARCHAR(100) DECLARE @getid CURSOR  SET @getid = CURSOR FOR SELECT table.id,        table.name FROM   table  OPEN @getid FETCH NEXT FROM @getid INTO @id, @name WHILE @@FETCH_STATUS = 0 BEGIN     EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name     FETCH NEXT     FROM @getid INTO @id, @name END  CLOSE @getid DEALLOCATE @getid 

Modified to show multiple parameters from the table.

like image 69
XN16 Avatar answered Sep 23 '22 08:09

XN16