In C# language we use continue
statement in a loop to move to next iteration. But in using Cursor in TSQL how can I perform the same. Let say I have,
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;
You can simply skip the record by calling the FETCH NEXT . With this approach you don't have to wrap the whole logic in a If statement instead you'll move to the next one record skipping the current record.
@@FETCH_STATUS (Transact-SQL)This function returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.
While SQL While loop is quicker than a cursor, reason found that cursor is defined by DECLARE CURSOR. Every emphasis of the loop will be executed inside system memory and consuming required server assets.
The CONTINUE statement stops the current iteration of the loop and starts the new one. The following illustrates the syntax of the CONTINUE statement: WHILE Boolean_expression BEGIN -- code to be executed IF condition CONTINUE; -- code will be skipped if the condition is met END.
CONTINUE
does go back to the start of the WHILE
loop, but it's not exactly like in C#, since the cursor looping idiom in T-SQL is broken into two separate statements, and the WHILE
is the second of them - the cleanest, requiring the least repetition, may be our old friend 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With