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
I usually do it this way when it's a quite a few rows:
(On larger datasets i'd use one of the solutions mentioned above though).
You could do something like this: order your table by e.g. CustomerID (using the AdventureWorks
Sales.Customer
sample table), and iterate over those customers using a WHILE loop:That should work with any table as long as you can define some kind of an
ORDER BY
on some column.DELIMITER //
Generally speaking I always look for a set based approach (sometimes at the expense of changing the schema).
However, this snippet does have its place..
If you can turn the stored procedure into a function that returns a table, then you can use cross-apply.
For example, say you have a table of customers, and you want to compute the sum of their orders, you would create a function that took a CustomerID and returned the sum.
And you could do this:
Where the function would look like:
Obviously, the example above could be done without a user defined function in a single query.
The drawback is that functions are very limited - many of the features of a stored procedure are not available in a user-defined function, and converting a stored procedure to a function does not always work.
This is a variation on the answers already provided, but should be better performing because it doesn't require ORDER BY, COUNT or MIN/MAX. The only disadvantage with this approach is that you have to create a temp table to hold all the Ids (the assumption is that you have gaps in your list of CustomerIDs).
That said, I agree with @Mark Powell though that, generally speaking, a set based approach should still be better.