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;
CONTINUE
はWHILE
ループの先頭に戻りますが、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;
この方法で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;
これを試してください-
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