I'm using transactions for the first time in the context of a stored procedure and I have a question. Using the following code:DECLARE @Count int, @ID intSELECT @ID = ID FROM MyTable WHERE blah, blah, blahSET @Count = @@ROWCOUNTIF @Count = 0 BEGIN SET @ResultMessage = 'There was no match' SET @Confirmation = 1 ENDELSE --if it exists update fields BEGIN BEGIN TRAN UPDATE AnotherTable SET This = That WHERE ID = @ID IF @@ERROR <> 0 --if transaction fails rollback transaction BEGIN ROLLBACK TRAN GOTO on_error END COMMIT TRAN SET @Confirmation = 0 SET @ResultMessage = 'Committed successfully' ENDon_error: SET @Confirmation = 1SET @ResultMessage = 'Failed and was rolled back'GO GO
This always runs the on_error label code. I have the following solution:DECLARE @Count int, @ID intSELECT @ID = ID FROM MyTable WHERE blah, blah, blah SET @Count = @@ROWCOUNTIF @Count = 0 --if does not exist send back error code BEGIN SET @ResultMessage = 'There was no match in the database' SET @Confirmation = 1 ENDELSE --if it exists update fields BEGIN BEGIN TRAN UPDATE AnotherTable SET this = that WHERE ID = @ID IF @@ERROR <> 0 --if transaction fails rollback transaction BEGIN ROLLBACK TRAN GOTO on_error END COMMIT TRAN GOTO proc_end ENDon_error: SET @Confirmation = 1SET @ResultMessage = 'Failed and was rolled back'proc_end:SET @Confirmation = 0SET @ResultMessage = 'Committed successfully'GO
What I need to know is whether or not it is within good stored procedure coding practices. Thanks in advance.