[sql] Loop through all the rows of a temp table and call a stored procedure for each row

I have declared a temp table to hold all the required values as follows:

    DECLARE @temp TABLE
    (
    Password INT,
    IdTran INT,
    Kind VARCHAR(16)
    )

INSERT INTO @temp
SELECT  s.Password, s.IdTran, 'test'
from signal s inner join vefify v 
    on s.Password = v.Password 
and s.IdTran = v.IdTran 
and v.type = 'DEV' 
where s.[Type] = 'start' 
AND NOT EXISTS (SELECT * FROM signal s2
            WHERE s.Password = s2.Password 
            and s.IdTran = s2.IdTran 
            and s2.[Type] = 'progress' )

INSERT INTO @temp
SELECT  s.Password, s.IdTran, 'test'
FROM signal s inner join vefify v 
    on s.Password = v.Password 
and s.IdTran = v.IdTran 
and v.type = 'PROD' 
where s.[Type] = 'progress' 
AND NOT EXISTS (SELECT * FROM signal s2
            WHERE s.Password = s2.Password 
            and s.IdTran = s2.IdTran 
            and s2.[Type] = 'finish' )
            
            
            

Now i need to loop through the rows in the @temp table and and for each row call a sp that takes all the parameters of @temp table as input. How can I achieve this?

This question is related to sql sql-server stored-procedures foreach

The answer is


Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.

You may want to experiment with BulkCopy in your C# or VB.Net code.


You always don't need a cursor for this. You can do it with a while loop. You should avoid cursors whenever possible. While loop is faster than cursors.


You can do something like this

    Declare @min int=0, @max int =0 --Initialize variable here which will be use in loop 
    Declare @Recordid int,@TO nvarchar(30),@Subject nvarchar(250),@Body nvarchar(max)  --Initialize variable here which are useful for your

    select ROW_NUMBER() OVER(ORDER BY [Recordid] )  AS Rownumber, Recordid, [To], [Subject], [Body], [Flag]
            into #temp_Mail_Mstr FROM Mail_Mstr where Flag='1'  --select your condition with row number & get into a temp table

    set @min = (select MIN(Rownumber) from #temp_Mail_Mstr); --Get minimum row number from temp table
    set @max = (select Max(Rownumber) from #temp_Mail_Mstr);  --Get maximum row number from temp table

   while(@min <= @max)
   BEGIN
        select @Recordid=Recordid, @To=[To], @Subject=[Subject], @Body=Body from #temp_Mail_Mstr where Rownumber=@min

        -- You can use your variables (like @Recordid,@To,@Subject,@Body) here  
        -- Do your work here 

        set @min=@min+1 --Increment of current row number
    END

something like this?

DECLARE maxval, val, @ind INT;
SELECT MAX(ID) as maxval FROM table;

while (ind <= maxval  ) DO           

      select `value` as val from `table` where `ID`=ind;

      CALL fn(val);

      SET ind = ind+1;
end while;

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to stored-procedures

How to create temp table using Create statement in SQL Server? How do I pass a list as a parameter in a stored procedure? SQL Server IF EXISTS THEN 1 ELSE 2 Stored procedure with default parameters Could not find server 'server name' in sys.servers. SQL Server 2014 How to kill all active and inactive oracle sessions for user EXEC sp_executesql with multiple parameters MySQL stored procedure return value SQL Server: use CASE with LIKE SQL server stored procedure return a table

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?