23

在 C# 语言中,我们continue在循环中使用语句来移动到下一次迭代。但是在 TSQL 中使用 Cursor 时,我该如何执行相同的操作。假设我有,

DECLARE db_cursor CURSOR FOR SELECT age, name, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  
       --Do stuff 
       IF @myAge=1
       BEGIN
          -- Use continue here
       END    
       --Do stuff 


       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
4

3 回答 3

42

CONTINUE确实回到WHILE循环的开头,但它与 C# 中的不完全一样,因为 T-SQL 中的游标循环习惯用法被分成两个单独的语句,并且WHILE是其中的第二个 - 最干净,需要最少的重复,可能是我们的老朋友GOTO

DECLARE db_cursor CURSOR FOR SELECT age, name, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  
       --Do stuff 
       IF @myAge=1
       BEGIN
          Goto Cont
       END    
       --Do stuff 

Cont:
       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
于 2013-07-25T06:20:48.600 回答
13

您可以以这种方式使用 CONTINUE

DECLARE db_cursor CURSOR FOR SELECT age, name, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  
       --Do stuff 
       IF @myAge=1
       BEGIN

           FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
           CONTINUE;
       END    
       --Do stuff 


       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
于 2014-06-24T15:15:27.223 回答
2

试试这个——

DECLARE 
       @myName VARCHAR(256)
     , @myAge INT
     , @myFavoriteColor VARCHAR(40)

DECLARE cursor_name CURSOR FAST_FORWARD READ_ONLY FOR
     SELECT age, name, color 
     FROM [table]

OPEN db_cursor

FETCH NEXT FROM db_cursor INTO 
       @myName
     , @myAge
     , @myFavoriteColor

WHILE @@FETCH_STATUS = 0 BEGIN

       IF @myAge = 1 BEGIN

            FETCH NEXT FROM db_cursor INTO 
                   @myName
                 , @myAge
                 , @myFavoriteColor

       END    

       FETCH NEXT FROM db_cursor INTO 
            @myName
          , @myAge
          , @myFavoriteColor

END

CLOSE db_cursor
DEALLOCATE db_cursor
于 2013-07-25T06:05:42.347 回答