How can one call a stored procedure for each row in a table, where the columns of a row are input parameters to the sp without using a Cursor?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
For SQL Server 2005 onwards, you can do this with CROSS APPLY and a table-valued function.
Just for clarity, I'm referring to those cases where the stored procedure can be converted into a table valued function.
I'd use the accepted answer, but another possibility is to use a table variable to hold a numbered set of values (in this case just the ID field of a table) and loop through those by Row Number with a JOIN to the table to retrieve whatever you need for the action within the loop.
This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.
Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.
I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.
A better solution for this is to
This was you get a clean table-formatted output. While if you run SP for every row, you get a separate query result for each iteration which is ugly.
Ok, so I would never put such code into production, but it does satisfy your requirements.
Marc's answer is good (I'd comment on it if I could work out how to!)
Just thought I'd point out that it may be better to change the loop so the
SELECT
only exists once (in a real case where I needed to do this, theSELECT
was quite complex, and writing it twice was a risky maintenance issue).