Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Exceptions in SQL Server
1. EXCEPTIONS:
1. In programs 3 types of error will occur. They are compilation errors, logical errors and runtime
errors
2. Compilation errors and logical errors can be rectified or managed by the programmer
3. Runtime error will manage or rectified by using exception.
4. Runtime errors are called exceptions.in SQLSERVER 2000 and OLD versions @@ERROR predefined
global variable is used.
5. In sqlserver 2005 & in next versions try-catch block will be used.
SYNTAX:
BEGIN TRY
STATEMENT(S)
END TRY
BEGIN CATCH
STATEMENT(S)
END CATCH
NOTE:
1. All the statements will be in try block when runtime occurs try block will through error to the
catch block
2. Catch block will rectify the error or it will manage the error so that program can run successfully
Example
CREATE PROCEDURE PRCDIV @A INT,@B INT
AS
BEGIN
BEGIN TRY
DECLARE @C INT
PRINT @C=@A/@B
PRINT @C
END TRY
2. BEGIN CATCH
SELECT ERROR_NUMBER(),ERROR_MESSAGE()
END CATCH
END
NOTE:
ERROR_NUMBER() and ERROR_MESSAGE() are used to display system error number and system
error message
CREATE PROCEDURE TO CHECK WHETHER THE GIVEN TABLE IS EXISTING OR NOT
CREATE PROCEDURE PRC2
AS
BEGIN
BEGIN TRY
DECLARE @S NVARCHAR(100)
SELECT @S=’SELECT * FROM EMPLOYEE’
EXEC SP_EXECUTE SQL@S
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() NUMBER
ERROR_MESSAGE() MESSAGE
END CATCH
END