Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue from top in SQL SERVER Cursor?

Tags:

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; 
like image 788
Imran Qadir Baksh - Baloch Avatar asked Jul 25 '13 06:07

Imran Qadir Baksh - Baloch


People also ask

How do I skip a row in a SQL 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.

What is @@ Fetch_status in SQL Server?

@@FETCH_STATUS (Transact-SQL)This function returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

Which is faster cursor or loop?

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.

What is continue in SQL Server?

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.


1 Answers

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; 
like image 59
Damien_The_Unbeliever Avatar answered Oct 23 '22 20:10

Damien_The_Unbeliever