I have a stored procedure of the general form below. Essentially 3 cursors which each perform INSERT
and UPDATE statements dynamically. If I wanted to add in a "BEGIN TRANSACTION" statement where would
I place this so that I don't get any of those
Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.
type errors. Should it be after the XACT_ABORT statement and then wrap all proceeding lines in a BEGIN and END? Should there
be a begin transaction statement inside each cursor?
and UPDATE statements dynamically. If I wanted to add in a "BEGIN TRANSACTION" statement where would
I place this so that I don't get any of those
Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.
type errors. Should it be after the XACT_ABORT statement and then wrap all proceeding lines in a BEGIN and END? Should there
be a begin transaction statement inside each cursor?
Code:
CREATE PROCEDURE spMyProc
AS
BEGIN
SET XACT_ABORT OFF
CREATE TABLE #tblFoo ....
INSERT INTO #tblFoo ....
DECLARE @Cursor_Val1 INT
DECLARE @Cursor_Val2 VARCHAR(50)
DECLARE @Cursor_Val3 VARCHAR(50)
DECLARE @Cursor_Val4 VARCHAR(50)
DECLARE @Cursor_Counter INT
SET @Cursor_Counter = 0
-------------------------------------------------
-- CURSOR 1
-------------------------------------------------
DECLARE MyCursor cursor for
SELECT OrganisationRoleID, CurrentDepthID FROM #tblFoo
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3
WHILE @@fetch_status = 0
BEGIN
SET @Cursor_Counter = @Cursor_Counter + 1
SET @Cursor_Val2 = ....
SELECT ...
IF @Cursor_Val4 IS NOT NULL
BEGIN
UPDATE #tblFoo
...
END
ELSE
BEGIN
UPDATE #tblFoo
...
END
SET @Cursor_Val4 = NULL
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3
END
CLOSE MyCursor
DEALLOCATE MyCursor
-------------------------------------------------
-- CURSOR 2
-------------------------------------------------
CREATE TABLE #tblBar ...
DECLARE MyCursor cursor for
SELECT * FROM #tblFoo
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3, @Cursor_Val4
WHILE @@fetch_status = 0
BEGIN
UPDATE ...
UPDATE ...
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3, @Cursor_Val4
END
CLOSE MyCursor
DEALLOCATE MyCursor
-------------------------------------------------
-- CURSOR 3
-------------------------------------------------
DECLARE MyCursor cursor for
SELECT ....
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3, @Cursor_Val2, @Cursor_Val4
WHILE @@fetch_status = 0
BEGIN
UPDATE ...
UPDATE ...
FETCH NEXT FROM MyCursor INTO @Cursor_Val1, @Cursor_Val3, @Cursor_Val2, @Cursor_Val4
END
CLOSE MyCursor
DEALLOCATE MyCursor
DROP TABLE #tblFoo
END
GO