web-dev-qa-db-ja.com

SQL SERVERカーソルの先頭から続行しますか?

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;
19
user960567

CONTINUEWHILEループの先頭に戻りますが、T-SQLのカーソルループイディオムは2つの個別のステートメントに分割されており、WHILEは2番目のステートメントです。繰り返しが少ない、古い友人かもしれない 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;
31

この方法で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;
6
Habib Ullah

これを試してください-

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
3
Devart