I can rollback a transaction if an error occurs:
CREATE PROCEDURE [dbo].[MySproc]
(
@Param1 [int]
)
AS
BEGIN TRAN
SET NOCOUNT ON;
SELECT @Param1
UPDATE [dbo].[Table1]
SET Col2 = 'something'
WHERE Col1 = @Param1
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
RETURN -12
END
...
But if there are no entries in the Table1
with the Col1 = @Param1
transaction commits successfully, which is bad for me. I'd like to check if Col2 = 'something'
is really done. If not, then rollback with a particular return code.
If I try to insert @@rowcount
check after @@error
check, like the following:
CREATE PROCEDURE [dbo].[MySproc]
(
@Param1 [int]
)
AS
BEGIN TRAN
SET NOCOUNT ON;
SELECT @Param1
UPDATE [dbo].[Table1]
SET Col2 = 'something'
WHERE Col1 = @Param1
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
RETURN -12
END
IF @@ROWCOUNT = 0
BEGIN
ROLLBACK TRAN
RETURN -27
END
...
it always rollbacks at this point, because @@rowcount
evaluates the very last statement so it always equals 0
.
How in such a case to check both the @@error
and the number of rows affected?
Store both into your own variables in a single query, then check:
DECLARE @rc int
DECLARE @err int
SELECT @Param1
UPDATE [dbo].[Table1]
SET Col2 = 'something'
WHERE Col1 = @Param1
SELECT @rc = @@ROWCOUNT,@err = @@ERROR
IF @err <> 0
BEGIN
ROLLBACK TRAN
RETURN -12
END
IF @rc = 0
BEGIN
ROLLBACK TRAN
RETURN -27
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With