سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top