Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Commit and Rollback

Author  Topic 

kalyformin
Starting Member

15 Posts

Posted - 2007-12-15 : 14:30:03
I have a cursor loop through a set of records that looks something like this.

OPEN database_cursor

FETCH NEXT FROM database_cursor
INTO @iID

WHILE @@FETCH_STATUS = 0

BEGIN

update table 1

update table
......

FETCH NEXT FROM database_cursor
INTO @iID

END

CLOSE database_cursor
DEALLOCATE database_cursor

Is there a way i could put all the UPDATE statements within a transaction. either everything goes or nothing.THnaks

Thanks,


spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2007-12-15 : 15:11:33
why have a cursor at all?

set xact_abort on
begin tran
--your stuff
commit

set xact_abort on means that the transacion will rollback if an error happens.

_______________________________________________
Causing trouble since 1980
blog: http://weblogs.sqlteam.com/mladenp
SSMS Add-in that does a few things: www.ssmstoolspack.com <- new version out
Go to Top of Page

kalyformin
Starting Member

15 Posts

Posted - 2007-12-15 : 16:58:12
I have the cursor to perform above actions in a loop for a specific condition.
I'd like to commit/rollback changes if the script execution is stopped or gets killed for some reason.
Go to Top of Page

dataguru1971
Master Smack Fu Yak Hacker

1464 Posts

Posted - 2007-12-15 : 18:35:20
YOu still don't need a cursor, you can update using a where clause to specify the conditions. SQL is works best with SET based operations, not row level operations which are more intensive for resource use.

If the process is killed, it will rollback by default. Or as suggested you place the Begin Trans/ Commit lines in...if it fails or is otherwise cancelled, the operation will rollback.



Poor planning on your part does not constitute an emergency on my part.

Go to Top of Page
   

- Advertisement -