查询在while循环中不能正常工作

时间:2012-04-14 10:30:49

标签: sql tsql sql-server-2005

我正在尝试插入一个While循环。

              DECLARE @CurrentOffer int  =121
        DECLARE @OldestOffer int  = 115
        DECLARE @MinClubcardID bigint=0
              DECLARE @MaxClubcardID bigint=1000
                    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

我的TempClub表始终仅检查前100条记录。我的TempClub表有3000条记录。 我需要使用ClubTransaction_121,ClubTransaction_120,ClubTransaction_119表检查我所有的3000张记录卡。

2 个答案:

答案 0 :(得分:1)

第8行中的SELECT查询仅返回前100个项目

SELECT top (100) clubcard from TempClub ...

如果要检索所有项目,请删除语句的top (100)部分

SELECT clubcard from TempClub ...

答案 1 :(得分:1)

为了进行批处理类型处理,您需要将@MinClubcardID设置为处理的最后一个ID加1,并包含ORDER BY ID以确保按顺序返回记录。

但是......我不会使用主键作为我的“索引”的方法。您正在寻找的是一种基本的分页模式。在SQL Server 2005+中,Microsoft引入了row_number()函数,这使得分页更加容易。

例如:

 DECLARE @T TABLE (clubcard INT)

 DECLARE @start INT
 SET @start = 0

 WHILE(1=1)
 BEGIN
   INSERT @T (clubcard)
   SELECT TOP 100 clubcard FROM 
   (
      SELECT clubcard,
      ROW_NUMBER() OVER (ORDER BY ID) AS num
      FROM dbo.TempClub
   ) AS t
   WHERE num > @start

  IF(@@ROWCOUNT = 0) BREAK;

  -- update counter
  SET @start = @start + 100

  -- process records found

  -- make sure temp table is empty
  DELETE FROM @T
END