Droping out of a cusor

  • Hi what’s the best to way to drop out of a cursor if a condition is meet?

    Many thanks

  • You are looking for the BREAK keyword.

    a simple example to break out of what would otherwise be an endless loop:

    --RAISERROR immediate message

    --print error immediately in batch

    DECLARE

    @i INT,

    @err VARCHAR(100)

    --set @i=1

    WHILE 0 = 0

    BEGIN

    SET @err = 'Progress So Far: Step ' + CONVERT(VARCHAR(30), ISNULL(@i, 1)) + ' completed.'

    RAISERROR (@err,

    0,

    1) WITH nowait

    WAITFOR delay '00:00:02'

    SET @i=ISNULL(@i, 1) + 1

    IF @i > 5

    BREAK;

    END

    PRINT 'We Broke out of the loop!'

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Thats great thank you

  • Edward-445599 (5/1/2013)


    Hi what’s the best to way to drop out of a cursor if a condition is meet?

    Many thanks

    Are you sure you even need a cursor? Given that you want to break out of one I am guessing you are doing some sort of RBAR processing. Maybe the best way out of your cursor is to not have one at all.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Sean Lange (5/1/2013)


    Edward-445599 (5/1/2013)


    Hi what’s the best to way to drop out of a cursor if a condition is meet?

    Many thanks

    Are you sure you even need a cursor? Given that you want to break out of one I am guessing you are doing some sort of RBAR processing. Maybe the best way out of your cursor is to not have one at all.

    +100

    Best,
    Kevin G. Boles
    SQL Server Consultant
    SQL MVP 2007-2012
    TheSQLGuru on googles mail service

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply