Transactions & Cursors

  • If you wrap a cursor in a "Begin Tran" statement and then have a "IF Error=!0 Rollback" statement after the Deallocate, will the Rollback catch every update / insert that was inside the cursor and roll it back?

    My instincts say yes, but part of me also says no. So please enlighten me.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

  • It will, a cursor doesn't change anything.

    Example:

    CREATE TABLE #a(id int IDENTITY(1,1), a char(1))

    INSERT INTO #a(a)

    SELECT 'a' UNION ALL

    SELECT 'a' UNION ALL

    SELECT 'a' UNION ALL

    SELECT 'a'

    GO

    DECLARE @id int

    BEGIN TRAN

    DECLARE Test CURSOR FOR

    SELECT id FROM #a

    OPEN Test

    FETCH NEXT FROM Test

    INTO @id

    WHILE @@FETCH_STATUS = 0

    BEGIN

    UPDATE #a

    SET a = 'b'

    WHERE id = @id

    FETCH NEXT FROM Test

    INTO @id

    END

    CLOSE Test

    DEALLOCATE Test

    SELECT * FROM #a

    ROLLBACK TRAN

    SELECT * FROM #a

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • Thanks, Garadin, for both the response and the test code. It's appreciated.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

Viewing 3 posts - 1 through 3 (of 3 total)

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