I'm using transactions for the first time in the context of a stored procedure and I have a question. Using the following code:
This always runs the on_error label code. I have the followinvnng solution:
What I need to know is whether or not it is within good stored procedure coding practices. Thanks in advance.
Code:
DECLARE @Count int,
@ID int
SELECT @ID = ID FROM MyTable WHERE blah, blah, blah
SET @Count = @@ROWCOUNT
IF @Count = 0
BEGIN
SET @ResultMessage = 'There was no match'
SET @Confirmation = 1
END
ELSE --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'
END
on_error:
SET @Confirmation = 1
SET @ResultMessage = 'Failed and was rolled back'
GO
Code:
DECLARE @Count int,
@ID int
SELECT @ID = ID FROM MyTable WHERE blah, blah, blah
SET @Count = @@ROWCOUNT
IF @Count = 0 --if does not exist send back error code
BEGIN
SET @ResultMessage = 'There was no match in the
database'
SET @Confirmation = 1
END
ELSE --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
END
on_error:
SET @Confirmation = 1
SET @ResultMessage = 'Failed and was rolled back'
proc_end:
SET @Confirmation = 0
SET @ResultMessage = 'Committed successfully'
GO