-3

可能重复:
查询在 while 循环中无法正常工作

我有一个 WHILE 循环,我试图在其中插入

DECLARE @CurrentOffer int  =121
DECLARE @OldestOffer int  = 115

WHILE 1 = 1
BEGIN
     INSERT INTO Temp WITH (TABLOCK)
        SELECT TOP (100) clubcard  
        FROM TempClub WITH (NOLOCK) 
        WHERE ID BETWEEN @MinClubcardand AND @MaxClubcard

     declare @sql varchar(8000)

     while @OldestOffer <= @CurrentOffer
     begin
          print @CurrentOffer
          print @OldestOffer

          set @sql = 'delete from Temp where Clubcard 
                      in (select Clubcard 
                          from ClubTransaction_' + convert(varchar, @CurrentOffer) +
                     ' with (nolock))'

          print (@sql)
          exec (@sql)

          SET @CurrentOffer = @CurrentOffer-1  

          IF @OldestOffer = @CurrentOffer
          begin
             -- my logic
          end
     end
END

我在这里做的是我将行批量插入表中Temp并检查表中是否存在ClubTransaction_121

如果确实退出,我需要在此处删除它,我的循环获取前 100 张俱乐部卡,然后检查ClubTransaction_121并移动以检查下一个报价,即 120

但是我的表Temp有 3000 行,需要ClubTransaction_121与所有行的表一起检查。

它只检查前 100 条记录,然后检查下一个 ClubTransaction_120。

我需要检查我所有的俱乐部卡所有 3000 行以及所有 ClubTransaction_121表格的ClubTransaction_120所有行ClubTransaction_119

4

1 回答 1

0

首先,我建议去掉 TABLOCK 和 NOLOCK,因为它们会导致数据不一致。

接下来在您的循环中的每次迭代中,我将 BEGIN TRANSACTION 和 COMMIT TRANSACTION 假设每个步骤在完成时都可以认为是好的,并且如果 10 个循环完成,并且第 11 个循环失败,则可以不回滚整个事务。

像这样的东西:

DECLARE @CurrentOffer int  =121
DECLARE @OldestOffer int  = 115

WHILE 1 = 1
BEGIN
    BEGIN TRANSACTION;
     INSERT INTO Temp 
        SELECT TOP (100) clubcard  
        FROM TempClub 
        WHERE ID BETWEEN @MinClubcardand AND @MaxClubcard

     declare @sql varchar(8000)

     while @OldestOffer <= @CurrentOffer
     begin
          print @CurrentOffer
          print @OldestOffer

          set @sql = 'delete from Temp where Clubcard 
                      in (select Clubcard 
                          from ClubTransaction_' + convert(varchar, @CurrentOffer)

          print (@sql)
          exec (@sql)

          SET @CurrentOffer = @CurrentOffer-1  

          IF @OldestOffer = @CurrentOffer
          begin
             -- my logic
          end
     end
    COMMIT TRANSACTION;
END
于 2012-04-14T15:31:07.010 回答