Juan Manuel M
Juan Manuel M

Reputation: 25

How to stop the execution of a cursor without leaving the result in warnings or errors?

I have the following procedure in SQL Server that has a cursor to scroll through the records of a SELECT, the idea is that when you find a record that meets certain condition , the process must stop there and return a result in the select what he found

DECLARE CURSOR_NAME CURSOR AS 

    SELECT cit_init, cit_end FROM citas 
    WHERE preser_id = @preser_id 

OPEN CURSOR_NAME 
FETCH NEXT FROM CURSOR_NAME INTO @VAR1_CURS, @VAR2_CURS
WHILE @@FETCH_STATUS = 0 
BEGIN

    IF (.....CONDITION.....)
    BEGIN

            ....ACTION...

        SELECT  @VAR1_CURS, @VAR2_CURS

            ----If the condition is fulfilled , you must stop the execution of the cursor

             CLOSE CURSOR_NAME

    END

    FETCH NEXT FROM CURSOR_NAME INTO @VAR1_CURS, @VAR2_CURS

END
CLOSE CURSOR_NAME
DEALLOCATE CURSOR_NAME

Upvotes: 1

Views: 6446

Answers (1)

Razvan Socol
Razvan Socol

Reputation: 5694

Inside the IF statement you can use a BREAK statement (instead of CLOSE CURSOR_NAME), to exit the WHILE loop.

Upvotes: 3

Related Questions