Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL transaction checking both @@ERROR and @@ROWCOUNT after a statement

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?

like image 761
rem Avatar asked Nov 13 '12 07:11

rem


Video Answer


1 Answers

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
like image 96
Damien_The_Unbeliever Avatar answered Oct 05 '22 22:10

Damien_The_Unbeliever