Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If the while loop hits the break command it comes out of the loop and if cursor hit the break command, how can it break entirely 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
like image 423
Gorige ashok kumar Avatar asked Feb 06 '15 06:02

Gorige ashok kumar


People also ask

How do you break out of a while loop in SQL?

In SQL Server, the BREAK statement is used when you want to exit from a WHILE LOOP and execute the next statements after the loop's END statement.

Which is better cursor or while loop in SQL Server?

Always confusing thing is which one is better; SQL While loop or cursor? 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.

Which command is used to terminate loops in SQL?

The EXIT statement can be used only inside a loop; you cannot exit from a block directly. PL/SQL lets you code an infinite loop.


1 Answers

You can give some condition in WHILE loop that iterates on cursor. First condition would be on @@FETCH_STATUS and other would be on which you want to break 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 BREAK statement

WHILE @@FETCH_STATUS = 0 
   BEGIN
      FETCH NEXT FROM Employee_Cursor;
      //your code
      if condition 
      BEGIN
          BREAK
      END 
   END;
CLOSE Employee_Cursor;
like image 149
Adil Avatar answered Oct 07 '22 02:10

Adil