2

How can I execute the sp_1 for every ProductId and get a result set?

EXEC sp_1 (SELECT ID FROM Products)
2

3 Answers 3

2

Try this way. No direct query it seems. execute sp for each row

or try this , make small changes if needed.Use temp table to get values out of sp. Use the below inside a sp if needed.

begin
declare @ID int
declare @temp table (col1 int)
declare cur cursor for select distinct ID from products
open cur
fetch next from cur into @ID
truncate table @temp
while(@@FETCH_STATUS=0)
begin
insert into @temp (<'cols/output from procedure'>) exec (@ID)
end
select * from @temp
end
Sign up to request clarification or add additional context in comments.

Comments

0

I would store the id's in a temp table and use a WHILE loop (AVOID CURSORS!)

DECLARE @prodid INT
SELECT prodid, 0 as Processed INTO #prod_ids FROM Products

WHILE EXISTS (SELECT prodid FROM #prod_ids WHERE Processed = 0)
BEGIN
     SELECT TOP 1 @prodid = prodid FROM #prod_ids WHERE Processed = 0
     EXEC sp_1(@prodid)
     UPDATE #prod_ids SET Processed = 1 WHERE prodid = @prodid
END

4 Comments

Not everyone would agree with you on avoiding cursors sqlteam.com/article/cursors-an-overview
@DeanOC, I would definitely. If by any alternative; cursor can be avoided then it should be.
@Rahul I try to avoid them myself, however they can be useful as long as you're aware of their limitations. This is one case where the speed difference in the loop construct may be inconsequential relative to executing a SP every cycle.'
@DeanOC, I am talking about in general and not specific to this question. About this question, can't really comment whether loop/cursor will be efficient cause I haven't done a benchmarking and without that if you say cursor will be better than loop then that just a speculation without any proof (at least to me).
0

With dynamic query in SQL Server:

declare @cadena varchar(max) = ''

select @cadena = @cadena + 'exec sp_1 ' + ltrim(ID) + ';'
from Products;

exec(@cadena);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.