2014-01-24 92 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