2014-01-24 88 views
1

我已经创建了一些表,计算存储过程和检索新的数据集回:运行存储过程多次动态

" DECLARE @maxVal int " + 
    " Set @maxVal = (SELECT ID FROM TableCustomers " + 
    " WHERE Service_ID = @Service_ID) " + 
    " execute SP_CaculateData @maxVal "; 

现在TableCustomers也有一个名为客户名称列和每CustmerName可以有多个的Service_ID的。 如何多次运行我的存储过程,全部取决于每个客户名称具有多少个服务。喜欢的东西:

execute SP_CaculateData @maxVal 
execute SP_CaculateData @maxVal 
execute SP_CaculateData @maxVal 
execute SP_CaculateData @maxVal 

我一直在阅读一些关于游标,但如果任何人都可以给我一个手听到我对此表示赞赏。

+0

另一个选择是做一个基于集合的操作 - 将所有的整数值传递给proc的修改版本,它接受一个表值参数,并且同时计算并返回所有结果? – StuartLC

回答

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 

我不能说这是否是将执行比光标更好的解决方案,但它应该完成工作。

+0

非常感谢!现在我有一个想法如何从那里移动 – MishMish

+0

欢迎您,很高兴提供帮助。 – agileMike