Attempt to Capture @@IDENTITY, @@ROWCOUNT, and @@ERROR : ERROR « System Settings « SQL Server / T-SQL Tutorial






4> CREATE TABLE T1(
5>   pk_col    int NOT NULL PRIMARY KEY CHECK (pk_col > 0),
6>   ident_col int NOT NULL IDENTITY (1,1)
7> )
8>
9> DECLARE
10>   @myerror    AS int
11> INSERT INTO T1 VALUES(0) -- violate the check constraint
12> SET @myerror = @@ERROR
13> IF @myerror = 2627
14>   PRINT 'PRIMARY KEY constraint violation'
15> ELSE IF @myerror = 547
16>   PRINT 'CHECK constraint violation'
17> GO
Msg 547, Level 16, State 1, Server J\SQLEXPRESS, Line 11
The INSERT statement conflicted with the CHECK constraint "CK__T1__pk_col__3C54ED00". The conflict occurred in database "master", table "dbo.T1", column 'pk_col'.
The statement has been terminated.
CHECK constraint violation
1>
2> --Attempt to Capture @@IDENTITY, @@ROWCOUNT, and @@ERROR
3> DECLARE
4>   @myerror    AS int,
5>   @myrowcount AS int,
6>   @myidentity AS int
7> INSERT INTO T1 VALUES(10) -- PK violation
8> SELECT @myidentity = @@IDENTITY,
9>        @myrowcount = @@ROWCOUNT,
10>        @myerror    = @@ERROR
11> PRINT '@myidentity: ' + CAST(@myidentity AS varchar)
12> PRINT '@myrowcount: ' + CAST(@myrowcount AS varchar)
13> PRINT '@myerror   : ' + CAST(@myerror AS varchar)
14> GO

(1 rows affected)

(1 rows affected)
@myidentity: 2

(1 rows affected)
@myrowcount: 1

(1 rows affected)
@myerror   : 0
1> --Output of Successful Attempt to Capture @@IDENTITY, @@ROWCOUNT, and @@ERROR
2>
3> drop table T1;
4> GO








26.6.ERROR
26.6.1.@@error is
26.6.2.Using @@ERROR
26.6.3.@@ERROR reset
26.6.4.SELECT 5 / 0
26.6.5.SELECT * FROM master.dbo.sysmessages WHERE error = @@ERROR
26.6.6.Attempt to Capture @@IDENTITY, @@ROWCOUNT, and @@ERROR
26.6.7.Parse exception
26.6.8.connection-level exception
26.6.9.Check the @@ERROR with if statement
26.6.10.A stored procedure that uses the @@ERROR system function
26.6.11.Observing line numbers in exceptions