2012-04-14 59 views
1

我有一個While循環,我嘗試插入。查詢在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條記錄。

回答

1

行中的SELECT查詢8名返回前100項

SELECT top (100) clubcard from TempClub ... 

如果你想要檢索的所有項目,免除您的發言

SELECT clubcard from TempClub ... 
+0

我的眼睛絆了這一點。在那裏你正在尋找一些複雜的... – 2012-04-14 10:57:54

+0

我正在做批處理插入數據,所以我想提取前100名,然後重複這個過程,直到我完成所有記錄 – happysmile 2012-04-14 11:04:01

+0

啊,我們的理解失敗。只是認爲你的英語水平有點高。 @Chris的答案是否可以接受,或者他沒有得到答案? – 2012-04-15 11:51:05

1

top (100)一部分。爲了做到批次您需要將@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