November 24, 2010 at 5:28 am
I have a cursor and transaction within the Procedure.The sample is given below.
Exe:
DECLARE cursor1 CURSOR FOR
SELECT Column1,column2,column3 FROM table1 WHERE ID = @ID
OPEN cursor1
FETCH NEXT FROM cursor1
INTO @Column1,@column2,@column3
WHILE @@FETCH_STATUS = 0
BEGIN
Update @table2 SET Column1 =@Column1,Column2 = @column3 where ID = @column2
FETCH NEXT FROM cursor1
INTO @Column1,@column2,@column3
END
CLOSE cursor1
DEALLOCATE cursor1
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
END CATCH
When there is failed transaction before close and deallocate cursor it rollbacks the transaction,
when procedure is executed next time will the cursor be closed and deallocated before declare.
When the transaction fails inside the cursor will the cursor be closed and deallocated?
Close cursor on commit enabled is set to false.
November 27, 2010 at 2:37 am
same doubt i had few days ago... people suggested me to check cursor_status to close and deallocate the cursor..
November 27, 2010 at 4:03 am
Why do you use a c.u.r.s.o.r. in the first place?
Wouldn't the following statement do the same without touching the table once for every row?
UPDATE table2
SET Column1 =t1.Column1,Column2 = t2.column3
FROM table1
INNER JOIN table2 ON table1.ID = t2.column2
WHERE t1.ID = @ID
November 28, 2010 at 10:03 pm
The cursor I have shown above is just an example the actual is more complicated than above.
November 28, 2010 at 10:17 pm
Ashwin M N (11/28/2010)
The cursor I have shown above is just an example the actual is more complicated than above.
Complexity changes nothing here. 99.9999% of the time, there is no need for a cursor or RBAR. Only when you're trying to do some admin to every table or every database is there a reason to resort to either.
Whatever...
Getting back to your problem, I see a COMMIT TRAN but I don't see a BEGIN TRAN anywhere. Where does that come into play in the code you posted?
--Jeff Moden
Change is inevitable... Change for the better is not.
November 28, 2010 at 10:48 pm
BEGIN TRY
BEGIN TRAN
DECLARE cursor1 CURSOR FOR
SELECT Column1,column2,column3 FROM table1 WHERE ID = @ID
OPEN cursor1
FETCH NEXT FROM cursor1
INTO @Column1,@column2,@column3
WHILE @@FETCH_STATUS = 0
BEGIN
Update @table2 SET Column1 =@Column1,Column2 = @column3 where ID = @column2
FETCH NEXT FROM cursor1
INTO @Column1,@column2,@column3
END
CLOSE cursor1
DEALLOCATE cursor1
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
END CATCH
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply