How to manually break the cursor in a while loop. in sql server

if while loop also having a break, if while loop hit break command it comes out of the loop and if cursor hit break command , how it come entire out of the while loop for example: DECLARE @CursorTest TABLE ( idcol INT , fld1 INT, fld2 INT, fld3 CHAR(800) ) INSERT INTO @CursorTest (fld1, fld2, fld3) SELECT 1, RAND() * 100 * DATEPART(ms, GETDATE()), LEFT(REPLICATE(CAST(NEWID() AS VARCHAR(36)),30),800) DECLARE @Variable1 INT, @Variable2 INT DECLARE CursorName CURSOR FAST_FORWARD FOR SELECT idcol FROM @CursorTest OPEN CursorName FETCH NEXT FROM CursorName INTO @Variable1 WHILE @@FETCH_STATUS = 0 BEGIN if (@Variable1 =10) BEGIN BREAK END PRINT CAST(@Variable1 AS VARCHAR(5)) FETCH NEXT FROM CursorName INTO @Variable1 END CLOSE CursorName DEALLOCATE CursorName if cursor hit break command , how it come entire out of the while loop 

if the while loop also has a break, if while while I exit the loop to interrupt the loop, and if the command presses the cursor on the cursor, then how does it exit the while loop

+6
source share
2 answers

You can specify some condition in the WHILE loop that iterates over the cursor. The first condition would be @@FETCH_STATUS , and the other would be the one on which you want to split the loop

 WHILE @@FETCH_STATUS = 0 OR @stopLoop = false BEGIN FETCH NEXT FROM Employee_Cursor; //your code if condition BEGIN @stopLoop = true END END; CLOSE Employee_Cursor; 

Using the BREAK statement

 WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM Employee_Cursor; //your code if condition BEGIN BREAK END END; CLOSE Employee_Cursor; 
+12
source

my code: DECLARE @ Variable1 INT, @ Variable2 INT DECLARE CursorName CURSOR FAST_FORWARD FOR SELECT idcol

 FROM CursorTest OPEN CursorName FETCH NEXT FROM CursorName INTO @Variable1 WHILE @@FETCH_STATUS = 0 BEGIN PRINT CAST(@Variable1 AS VARCHAR(5)) FETCH NEXT FROM CursorName INTO @Variable1 END CLOSE CursorName DEALLOCATE CursorName 

if the command to hit by clicking on the cursor, how did it exit entirely from the while loop

0
source

Source: https://habr.com/ru/post/982082/


All Articles