而SQL Server中的循环和游标代码

时间:2017-05-11 20:16:19

标签: sql-server

我有两个表:输入表和计算查询,它从输入表生成结果。我试图创建一个循环,通过循环将当前基本速率更新1位,然后查询计算根据新的增量基本速率更新当前金额,直到当前金额等于或大于目标金额。我有一个提供商ID可以正常工作,但如果我有多个ID,它不能正常工作我不知道我错过了什么。

输入表

Provider ID   | Current Base Rate
---------------------------------
A             |      650
B             |     640
C             |     670

计算查询:OpSummary

Provider ID | Current Amount    |     Target Amount
------------------------------------------------------
A           |        250        |           300
B           |        150        |          200
C           |        75         |         100

这是代码:

ALTER PROCEDURE [dbo].[SPOPLoopTest] 
AS
     Declare @targetAmount money
     Declare @BASERATE Float
     Declare @CurrentAllowed money

 Set @targetAmount = cast((Select Max(t.TargetAmount)from[dbo].[opsummary]as money)
 Set @BASERATE = (Select Max(CurrentBaseRate)from[dbo].[InputTable] t)
 Set @CurrentAllowed = cast((Select Max(t.CurrentAllowed)from [dbo].[opsummary]t)as money)


Declare OPHosp Cursor For select t.Provider_ID from InputTable t 
Open OPHosp
Fetch Next from OPHosp
While @@FETCH_STATUS = 0 
Begin
   while (Select Max(t.CurrentAllowed)from [dbo].[opsummary]t)<=(Select Max(t.TargetAmount)from [dbo].[opsummary] t )
   begin

       if @CurrentAllowed>=(Select Max(t.TargetAmount)from [dbo].[opsummary] t) 
          break; 

       else

       begin

           Exec [dbo].[SPOpSummary]
           update [dbo].[InputTable] set CurrentBaseRate = @BASERATE

           set  @BASERATE = @BASERATE+1

           continue;
       end;

    end

end

从OPHosp获取Next

关闭OPHosp 解除分配OPHosp

0 个答案:

没有答案