This seems like it should be something I already know. We need to run a bunch of sql updates in a transaction, and rollback if one of them fails. We also want to print a status message since we’ll be running a large number of these. This would be simple if I were doing it in a general purpose programming language. But I am trying to find a solution a team member can use that is just SQL. She has done this in MS SQL Server in the past with the pattern below. Is there an equivalently simple pattern for Oracle?
DECLARE @ErrorVar INT;
BEGIN TRANSACTION;
UPDATE MyTable1 SET MyColumn1 = 'JSMITH' where MyColumn1 = 'JOHN';
SET @ErrorVar = @@ERROR;
UPDATE MyTable2 SET MyColumn2 = 'JSMITH' where MyColumn2 = 'JOHN';
SET @ErrorVar = @ErrorVar + @@ERROR;
UPDATE MyTable SET LoginID = 'JSMITH' where LoginID = 'JOHN';
SET @ErrorVar = @ErrorVar + @@ERROR;
IF @ErrorVar <> 0
BEGIN
ROLLBACK TRANSACTION;
PRINT 'We had a problem with JSMITH and rolled back *****';
END;
ELSE
BEGIN
COMMIT TRANSACTION;
PRINT 'JSMITH Updated ok';
END;
GO
In SQLPlus, use the WHENEVER command to control behavior when an error occurs.
WHENEVER SQLERROR EXIT FAILURE ROLLBACK is fairly standard in our scripts.
Type HELP WHENEVER at the SQLPlus prompt for more info.