Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a SQL Query multiple times with different parameters

I have a SQL stored procedure that I need to execute several times with different parameters. Is it possible to execute a SQL-script of some kind that will execute multiple times with like an array or other data-structure of different parameters? Any thoughts on this?

like image 462
SoftwareSavant Avatar asked Mar 08 '26 18:03

SoftwareSavant


1 Answers

you can use a cursor (but if it's possible to restructure your code, try YS's answer):

EDIT: added FAST_FORWARD as per @YS's suggestion

DECLARE @param INT

-- getting your parameter from the table
DECLARE curs CURSOR LOCAL FAST_FORWARD FOR
    SELECT afield FROM atable WHERE ...

OPEN curs

FETCH NEXT FROM curs INTO @param

-- executing your stored procedure once for every value of your parameter     
WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC usp_stored_Procedure @param
    FETCH NEXT FROM curs INTO @param
END

CLOSE curs
DEALLOCATE curs
like image 131
Paolo Falabella Avatar answered Mar 11 '26 10:03

Paolo Falabella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!