执行以查询作为参数的存储过程

时间:2014-07-19 09:44:53

标签: sql sql-server stored-procedures

如何为每个ProductId执行sp_1并获取结果集?

EXEC sp_1 (SELECT ID FROM Products)

3 个答案:

答案 0 :(得分:2)

试试这种方式。似乎没有直接查询。 execute sp for each row

或尝试此操作,如果需要,可以进行小的更改。使用临时表从sp中获取值。如果需要,请在sp内部使用以下内容。

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

答案 1 :(得分:0)

我会将id存储在临时表中并使用WHILE循环(避免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

答案 2 :(得分:0)

在 SQL Server 中使用动态查询:

declare @cadena varchar(max) = ''

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

exec(@cadena);