May 4, 2003 at 9:05 am
I am creating a stored proc that will be used to process a group of records, one at a time. The proc will be handed one record at a time and will perform a series of UPDATE, DELETE, and INSERT statements into other relevant tables.
I would like to create transactional integrity by using a transaction that contains all of the 10 INS/UPD/DEL statements. This would be done to ensure the proc didnt fail somewhere in the middle, such as if it errored out on the last statement. I have experimented with @@rowcount and @@error, but was wondering if someone had a good way of doing this.
A generic example of how my proc currently looks is below:
@recvalue1 --this param is passed into the proc
Begin Transaction
UPDATE tbl1 SET @recvalue1 = ...
INSERT INTO tbl2 VALUES ...
DELETE ...
UPDATE tbl4 SET ...
UPDATE tbl5 SET ...
UPDATE tbl6 SET ...
INSERT INTO tbl9 SET ...
End
Thanks!
Andrew J. Hahn
Andrew J. Hahn
May 5, 2003 at 7:09 am
You're almost there:
CREATE PROCEDURE MyTransProc
@Param1 DataType
AS
BEGIN TRANSACTION
-- do update/delete
IF @@ERROR <> 0 BEGIN
ROLLBACK TRANSACTION
RAISERROR('My error' , 16 , 1)
END
-- Continue update/deletes followed by error handler above
-- Finally:
COMMIT TRANSACTION
May 5, 2003 at 8:38 am
I would suggest using XACT_ABORT; it will automatically rollback a transaction, and stop further statements from executing in the transaction when an error is encountered:
SET XACT_ABORT ON
BEGIN TRAN -- with XACT_ABORT, any error automatically rollsback the transaction
DELETE FROM TABLE1
DELETE FROM TABLE2
DELETE FROM TABLE3
COMMIT TRAN -- if we got this far and there were no errors, commit
SET XACT ABORT OFF
Lowell
May 5, 2003 at 3:29 pm
Thanks guys!
This helps a lot.
Andrew J. Hahn
May 6, 2003 at 5:35 pm
What if you're creating dynamic SQL Statements and executing them.
ie. @strSQL = 'UPDATE tablea set column a = 56'
execute sp_executesql @strSQL
Will XACT_ABORT still be effective in this case?
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply