运行存储过程多次动态 [英] Run a Stored Procedure multiple times dynamically

查看:90
本文介绍了运行存储过程多次动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

一种选择是使用whil​​e循环通过客户和服务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.

这篇关于运行存储过程多次动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆