Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SP for each row in the result of a query

Author  Topic 

AAAV
Posting Yak Master

152 Posts

Posted - 2010-05-27 : 15:36:58
I need a stored procedure to be run for each row in the result of a query and the results be output to a table.
what is the best way of doing it. I trying to avoid cursors or temp table.

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-05-27 : 16:26:00
Can you show us what you are trying to do?
Maybe we have way around.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-05-27 : 21:18:17
either make the stored procedure accept a group of values


or make it a user defined function and call using APPLY operator like

SELECT *
FROM {query here} q
CROSS APPLY dbo.Function(q.field,q.field,...) f


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

AAAV
Posting Yak Master

152 Posts

Posted - 2010-05-28 : 09:56:43
This is my objective... i have an vehicle id and cost of the vehicle
and i have to calculate something like say depreciation cost for the vehicle for 7 years(every month in the year)

so given a vehicle info this procedure/function will return 7 rows one each for 1-7 years.
I have to do it for around 6000 vehicles and get it on to a table.
(my task doesnt end there after that i need averages etc) but getting the values to the table will make me get there almost.
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2010-05-28 : 10:26:14
Use Visakh's suggestion. Create a table-valued function and use cross apply
INSERT INTO aTable
SELECT <columns from query>, <columns from function>
FROM {query here} q
CROSS APPLY dbo.Function(q.field,q.field,...) f

Jim


Everyday I learn something that somebody else already knew
Go to Top of Page
   

- Advertisement -