【问题标题】:Run a Stored Procedure multiple times dynamically动态多次运行存储过程
【发布时间】:2014-01-24 13:01:54
【问题描述】:

我创建了一个存储过程,它从某个表中计算并检索一个新的数据集:

  " 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

我一直在阅读有关光标的内容,但如果有人能帮我听一下,我将不胜感激。

【问题讨论】:

  • 另一种选择是进行基于集合的操作 - 将所有整数值传递给接受表值参数的 proc 的修改版本,并同时计算和返回所有结果?

标签: asp.net sql database stored-procedures


【解决方案1】:

一种选择是使用 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

我不能说这是否是一个比光标性能更好的解决方案,但它应该可以完成工作。

【讨论】:

  • 非常感谢!现在我知道如何从那里移动
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多