运行存储过程多次动态
我已经创建了一些表,计算存储过程和检索新的数据集回:
I have created a stored procedure that calculates from some table and retrieve a new dataset back:
" DECLARE @maxVal int " +
" Set @maxVal = (SELECT ID FROM TableCustomers " +
" WHERE Service_ID = @Service_ID) " +
" execute SP_CaculateData @maxVal ";
现在的TableCustomers也有一个名为客户名称列,每个CustmerName可以有多个的Service_ID的。
我怎样才能运行我的存储过程多次,都取决于每个客户名称有多少服务了。是这样的:
Now the TableCustomers also have a column called CustomerName and each CustmerName can have multiple Service_ID's. How can I run my stored procedure multiple times, all depends on how many services each CustomerName has. Something like:
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
我一直在阅读一些关于游标,但如果任何人都可以给我一个手听到我会AP preciate这一点。
I have been reading something about cursors, but if anyone can give me a hand hear I would appreciate that.
一种选择是使用while循环通过客户和服务IDS迭代:
One option is to use a while loop to iterate through the customers and service ids:
declare
@maxVal int
,@customerName varchar(200)
,@serviceID int
select @customerName = MIN(CustomerName)
from TableCustomers t
while(select COUNT(1)
from TableCustomers t
where t.CustomerName >= @customerName) > 0
begin
--here we are dealing w/ a specific customer
--loop through the serviceIDs
select @serviceID = MIN(Service_ID)
from TableCustomers t
where t.CustomerName = @customerName
while(select COUNT(1)
from TableCustomers t
where t.CustomerName = @customerName
and t.Service_ID >= @serviceID) > 0
begin
select @maxVal = MAX(Id)
from TableCustomers t
where t.Service_ID = @serviceID
execute SP_CalculateData @maxVal
select @serviceID = MIN(Service_ID)
from TableCustomers t
where t.CustomerName = @customerName
and t.Service_ID > @serviceID
end
select @customerName = MIN(CustomerName)
from TableCustomers t
where t.CustomerName > @customerName
end
我不能说这是否将执行比光标更好的解决方案,但它应该完成这项工作。
I can't say whether or not this is a solution that will perform better than a cursor, but it should get the job done.