SQL Server How do you start though the cursor loop when a specific condition occurs

I have a SQL Server cursor. I want to skip one loop iteration when a specific condition occurs. A break pushes you out of the cursor loop and continues, it seems, does nothing.

Is there a team that says, “Hey, this record is not good, so let's skip it and work on the next one.”

By the way, I know that cursors are evil, like drivers who drive 43 miles per hour on the carriageway, but, as is often the case in software, I got stuck with it.

thanks

+6
sql-server
source share
5 answers

Why don't you just use the if statement:

IF condition exists that I want to update THEN BEGIN .... END Fetch Next 
+7
source share

if you code your loop with the extraction below (with the initial selection before the loop), continue to just jump to the top and process the same line again. you can use GOTO to go to the extraction part at the bottom or restructure the cycle to extract at the top and cointinue will work.

you can change your loop to use goto ...

 ... ... if <condition> BEGIN GOTO Fetch_Next END .... .... Fetch_Next: FETCH NEXT FROM ... 

Here is an example code for only one sample at the top of the loop, the continuation will work:

 DECLARE <cursor_name> CURSOR FOR SELECT FROM WHERE FOR READ ONLY --populate and allocate resources to the cursor OPEN <cursor_name> --process each row WHILE 1=1 BEGIN FETCH NEXT FROM <cursor_name> INTO @a, @b, @c --finished fetching all rows? IF @@FETCH_STATUS <> 0 BEGIN --YES, all done fetching --exit the loop BREAK END --IF finished fetching --do something here-- --do something here-- IF <your condition> BEGIN CONTINUE -- fetch next row END --do something here-- --do something here-- END --WHILE --close and free the cursor resources CLOSE <cursor_name> DEALLOCATE <cursor_name> 
+9
source share

It might be easier to answer if we knew what the cursor code looks like. Perhaps you can enter an if statement that checks the condition and only does something if the condition is missing.

0
source share

The cheap answer is to insert an IF block: the start loop / IF string is good BEGIN ... END / end loop.

0
source share

I have never found an SQL cursor that I could not delete after thinking, and the performance gain is usually huge. Is there a reason why you cannot select only the lines that you want to work on, rather than perform line-by-line processing?

0
source share

All Articles