Check the @@ERROR with if statement : ERROR « System Settings « SQL Server / T-SQL Tutorial






11> create table Billings (
12>     BankerID           INTEGER,
13>     BillingNumber      INTEGER,
14>     BillingDate        datetime,
15>     BillingTotal       INTEGER,
16>     TermsID            INTEGER,
17>     BillingDueDate     datetime ,
18>     PaymentTotal       INTEGER,
19>     CreditTotal        INTEGER
20>
21> );
22> GO
1>
2> INSERT INTO Billings VALUES (1, 1, '2005-01-22', 165, 1,'2005-04-22',123,321);
3> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (2, 2, '2001-02-21', 165, 1,'2002-02-22',123,321.);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (3, 3, '2003-05-02', 165, 1,'2005-04-12',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (4, 4, '1999-03-12', 165, 1,'2005-04-18',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (5, 5, '2000-04-23', 165, 1,'2005-04-17',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (6, 6, '2001-06-14', 165, 1,'2005-04-18',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (7, 7, '2002-07-15', 165, 1,'2005-04-19',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (8, 8, '2003-08-16', 165, 1,'2005-04-20',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (9, 9, '2004-09-17', 165, 1,'2005-04-21',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (0, 0, '2005-10-18', 165, 1,'2005-04-22',123,321);
2> GO

(1 rows affected)
1>
2>
3> CREATE PROC spInsertBilling
4>        @BankerID    int,           @BillingNumber  varchar(50),
5>        @BillingDate smalldatetime, @BillingTotal   money,
6>        @TermsID     int,           @BillingDueDate smalldatetime
7> AS
8> DECLARE @ErrorVar int
9> INSERT Billings (BankerID)
10> VALUES (@BankerID)
11> SET @ErrorVar = @@ERROR
12> IF @ErrorVar <> 0
13>     BEGIN
14>         IF @ErrorVar = 547
15>             PRINT 'Not a valid BankerID!'
16>         ELSE
17>             PRINT 'An unknown error occurred.'
18>         RETURN @ErrorVar
19>     END
20> GO
1>
2> DECLARE @ReturnVar int
3> EXEC @ReturnVar = spInsertBilling
4>      799,'ZXK-799','2002-07-01',299.95,1,'2001-08-01'
5> PRINT 'Return code was: ' + CONVERT(varchar,@ReturnVar)
6> GO

(1 rows affected)

(1 rows affected)
Return code was: 0
1>
2>
3> drop PROC spInsertBilling;
4> GO
1>
2>
3> drop table Billings;
4> GO
1>








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