Monday 16 December 2013

Error Handling with THROW clause at SQL 2012


Introduction

Before MS SQL 2005 developer knows how hard to trap an error by using @@ERROR variable value. But from MS SQL 2005 we use TRY… CATCH blog to trap an error. It is so easy that all the SQL developer is just flying on the sky.

So what's new in MS SQL 2012
As a simple question is that what's new at MS SQL 2012 for Error handling as we are very happy with MS from MS SQL 2005 onward.

Yes MS is now trying us to send at Moon surface with SQL 2012.  Just a recall of TRY …CATCH block of Error handling.

 BEGIN
   DECLARE @v_NO       INT;
   DECLARE @v_ErrSen   INT,
           @v_ErrMsg   VARCHAR(max),
           @v_ErrState INT;
          
   BEGIN TRY
        SET @v_NO = 1000;
        SET @v_NO = @v_NO / 0;
   END TRY
   BEGIN CATCH
       SET @v_ErrSen = ERROR_SEVERITY();
       SET @v_ErrMsg = ERROR_MESSAGE();
       SET @v_ErrState = ERROR_STATE();
      
       RAISERROR(@v_ErrMsg, @v_ErrSen, @v_ErrState);
   END CATCH
END

Please look at the BEGIN CATCH… END CATCH section. Here we use RAISERROR() which takes three parameters.

IN MS SQL 2012 There is no need to understand RAISERROR() just Use THROW only

Code sample is given bellow

BEGIN
   BEGIN TRY
        SET @v_NO = 1000;
        SET @v_NO = @v_NO / 0;
   END TRY
   BEGIN CATCH
       THROW;
   END CATCH
END

Is it not easier then the complex RAISERROR(). A new developer can set it easily at SQL 2012.

Thanks to MS for that.



Hope you like it.




Posted by: MR. JOYDEEP DAS


1 comment: