الثلاثاء، 11 أكتوبر 2011

Handling errors in SQL Server

/* @@ERROR */

-- Displays System defined with Error number severity and Description
SELECT * from master..sysmessages

-- Get the data from authors TABLE
USE pubs
SELECT * from authors
GO
--Reports information about a database object
sp_help authors


/* trapping the error */

-- Violate the format implemented by the check constraint
DECLARE @errint int
UPDATE authors
SET Zip = '123'
WHERE au_id = '213-46-8915'
SELECT @errint = @@ERROR
IF @errint = 547
      PRINT 'This is clear viloation of Check Constraint'
GO


-- CREATE a TABLE TestError
CREATE TABLE TestError
(
      ecode char(4) not null,
      ename varchar(20)
)


--INSERT null VALUES INTO the not null column and check for the @@ERROR value in the PRINT
-- statement
INSERT INTO TestError VALUES(null,'Shyam')
IF @@ERROR <> 0
      PRINT ' Error inserting INTO TABLE TestError ' + CONVERT(char(5),@@ERROR)
ELSE
      PRINT ' VALUES inserted INTO TABLE TestError ' + CONVERT(char(5),@@ERROR)
SELECT @@ERROR
GO

Notes
-   <> (Not Equal To)
Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand is not equal to the right operand; otherwise, the result is FALSE. If either or both operands are NULL.



-- It is always better to store the error value in a variable and then check it
DECLARE @errint int
INSERT INTO TestError VALUES(null,'Shyam')
SELECT @errint = @@ERROR
IF @errint <> 0
BEGIN
      PRINT '           Error INSERTing INTO TABLE TestError '
      PRINT '           The value of @@ERROR is ' + CONVERT(char(5),@@ERROR)
      PRINT '           The value of @errint is  ' + CONVERT(char(5),@errint)
END
ELSE
BEGIN
      PRINT ' VALUES INSERTed INTO TABLE TestError ' + CONVERT(char(5),@@ERROR)
END
GO

0 التعليقات: