3

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?

Abel
  • 56,041
  • 24
  • 146
  • 247
SoftwareSavant
  • 9,467
  • 27
  • 121
  • 195
  • Where do the parameters come from? A DB table? – John Pick Mar 05 '12 at 20:22
  • yep. A particular column in a table no less. – SoftwareSavant Mar 05 '12 at 20:23
  • 1
    It is possible to loop through the values of a column in a table and use them as parameters in a stored procedure call. But, that could be slow. Sometimes it is better (if it's even possible) to rewrite the stored procedure as non-procedural SQL. Of course, you haven't shown your code, so it is impossible to say what's best in your case. – John Pick Mar 05 '12 at 20:27

2 Answers2

5

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
Community
  • 1
  • 1
Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
  • 4
    Consider using `FAST_FORWARD` for added performance if cursor is read only & you're only moving forward. ie: `DECLARE curs CURSOR LOCAL FAST_FORWARD FOR...` – YS. Mar 05 '12 at 20:29
5

I'd probably restructure the design a bit to fit the need (to workaround the cursor) - ie:

  • insert values to be executed in stored proc into a temp table, then call the stored proc (the stored proc will then read the temp table)

  • call stored proc using table-valued parameter

YS.
  • 1,808
  • 1
  • 19
  • 33