Tuesday, December 3, 2013

SQL Server THROW - Similar to RAISERROR

As a part of SQL Server 2012 T-SQL Enhancements, here is one new feature under error handling section named "THROW", similar to RAISERROR function in previous SQL Server versions.

Data Validation is a process of checking values in one or more columns. In stored procedures, its very important to implement the data validation process. So, chances of getting data validation are very common.

The below stored procedures illustrates the usage of THROW statement for error handling.




Stored Procedure Creation:
CREATE PROCEDURE dbo.sp_InsertEmployee
@EMPNO NUMERIC(4,0),
@ENAME VARCHAR(50),
@JOB VARCHAR(50),
@MGR NUMERIC(4,0),
@SAL DECIMAL(7,2),
@COMM DECIMAL(7,2),
@DEPTNO NUMERIC(2,0)
AS
BEGIN

SET NOCOUNT ON;

IF EXISTS (SELECT * FROM dbo.DEPT WHERE DEPTNO = @DEPTNO)
INSERT INTO dbo.EMP (EMPNO, ENAME, JOB, MGR, SAL, COMM, DEPTNO)
VALUES (@EMPNO, @ENAME, @JOB, @MGR, @SAL, @COMM, @DEPTNO);

ELSE
THROW 50001, 'Invalid DEPTNO Entry!', 1

END

Stored Procedure Execution:
EXECUTE dbo.sp_InsertEmployee 2222, 'SAM', 'MANAGER', 7839, 4500, 500, 60



I have passed an invalid department number 60 and so SQL Server THROWs the customised error defined in the stored procedure. Please check the above snip.



No comments:

Post a Comment