Friday, June 8, 2012

SQL - Cursor close on commit


-------------------------------------------------------------------------------
-- SET CURSOR_CLOSE_ON_COMMIT
-------------------------------------------------------------------------------
SET NOCOUNT ON

-- Create a testing table
IF OBJECT_ID('CursorT1') IS NOT NULL
DROP TABLE CursorT1
GO

CREATE TABLE CursorT1 (
   a INT
)
GO

-- Insert testing records
INSERT INTO CursorT1 VALUES (1)
INSERT INTO CursorT1 VALUES (2)
GO

-- Cursor close on commit on
PRINT '-- SET CURSOR_CLOSE_ON_COMMIT ON'
GO
SET CURSOR_CLOSE_ON_COMMIT ON
GO

PRINT '-- BEGIN TRAN'
-- Begin a trasaction
BEGIN TRAN

-- Declare a cursor
PRINT '-- Declare and open cursor'
DECLARE testcursor CURSOR FOR
SELECT a FROM CursorT1

-- Open a cursor
OPEN testcursor
PRINT '-- Commit tran'

-- Commit a trasaction
COMMIT TRAN

PRINT '-- Try to use cursor'
FETCH NEXT FROM testcursor
-- Close and deallocate
CLOSE testcursor
DEALLOCATE testcursor
GO

-- Off commit
PRINT '-- SET CURSOR_CLOSE_ON_COMMIT OFF'
GO
SET CURSOR_CLOSE_ON_COMMIT OFF
GO

-- Begin a trasaction again
PRINT '-- BEGIN TRAN'
BEGIN TRAN

-- A new cursor
PRINT '-- Declare and open cursor'
DECLARE testcursor CURSOR FOR
SELECT a
FROM CursorT1

-- Open
OPEN testcursor
PRINT '-- Commit tran'

-- Commit, but it couldn't impact cursor
COMMIT TRAN
PRINT '-- Try to use cursor'
FETCH NEXT FROM testcursor

-- Close and deallocate
CLOSE testcursor
DEALLOCATE testcursor
GO
DROP TABLE CursorT1;
GO

No comments:

Post a Comment