我创建了一个存储过程,从一些表中计算并检索一个新的数据集:
" DECLARE @maxVal int " +
" Set @maxVal = (SELECT ID FROM TableCustomers " +
" WHERE Service_ID = @Service_ID) " +
" execute SP_CaculateData @maxVal ";
现在,TableCustomers还有一个名为CustomerName的列,每个CustmerName可以有多个Service_ID。 如何多次运行我的存储过程,所有这些都取决于每个CustomerName有多少服务。类似的东西:
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
execute SP_CaculateData @maxVal
我一直在阅读有关游标的内容,但是如果有人能帮助我,我会很感激。
答案 0 :(得分:2)
一种选择是使用while循环来遍历客户和服务ID:
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
我不能说这是否是一个比光标更好的解决方案,但它应该完成工作。