Error handling in sql server :)
Implements error handling for Transact-SQL that is similar to the exception handling in the Microsoft Visual C# and Microsoft Visual C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs in the TRY block, control is passed to another group of statements that is enclosed in a CATCH block
TRY..CATCH Syntax
- BEGIN TRY
- --T-SQL statements
- --or T-SQL statement blocks
- END TRY
- BEGIN CATCH
- --T-SQL statements
- --or T-SQL statement blocks
- END CATCH
Function Name Description ERROR_MESSAGE()
Returns the complete description of the error message ERROR_NUMBER()
Returns the number of the error ERROR_SEVERITY()
Returns the number of the Severity ERROR_STATE()
Returns the error state number ERROR_PROCEDURE()
Returns the name of the stored procedure where the error occurred ERROR_LINE()
Returns the line number that caused the error Create Table tblProduct --First table ( ProductId int NOT NULL primary key, Name nvarchar(50), UnitPrice int, QtyAvailable int ) Insert into tblProduct values(1, 'Laptops', 2340, 100) Insert into tblProduct values(2, 'Desktops', 3467, 50) Create Table tblProductSales --second table ( ProductSalesId int primary key, ProductId int, QuantitySold int ) Alter Procedure spSellProduct --Sp creation with the help of two table here we mention the userdeifne erro Raise error @ProductId int, @QuantityToSell int as Begin -- Check the stock available, for the product we want to sell Declare @StockAvailable int Select @StockAvailable = QtyAvailable from tblProduct where ProductId = @ProductId -- Throw an error to the calling application, if enough stock is not available if(@StockAvailable < @QuantityToSell) Begin Raiserror('Not enough stock available',16,1) End -- If enough stock available Else Begin Begin Tran -- First reduce the quantity available Update tblProduct set QtyAvailable = (QtyAvailable - @QuantityToSell) where ProductId = @ProductId Declare @MaxProductSalesId int -- Calculate MAX ProductSalesId Select @MaxProductSalesId = Case When MAX(ProductSalesId) IS NULL Then 0 else MAX(ProductSalesId) end from tblProductSales -- Increment @MaxProductSalesId by 1, so we don't get a primary key violation Set @MaxProductSalesId = @MaxProductSalesId + 1 Insert into tblProductSales values(@MaxProductSalesId, @ProductId, @QuantityToSell) if(@@ERROR <> 0) Begin Rollback Tran Print 'Rolled Back Transaction' End Else Begin Commit Tran Print 'Committed Transaction' End End End3. In the procedure, we are using Raiserror() function to return an error message back to the calling application, if the stock available is less than the quantity we are trying to sell. We have to pass atleast 3 parameters to the Raiserror() function. RAISERROR('Error Message', ErrorSeverity, ErrorState) Severity and State are integers. In most cases, when you are returning custom errors, the severity level is 16, which indicates general errors that can be corrected by the user. In this case, the error can be corrected, by adjusting the @QuantityToSell, to be less than or equal to the stock available. ErrorState is also an integer between 1 and 255. RAISERROR only generates errors with state from 1 through 127.Begin Transaction and Commit Transaction statements are wrapped between Begin Try and End Try block. If there are no errors in the code that is enclosed in the TRY block, then COMMIT TRANSACTION gets executed and the changes are made permanent. On the other hand, if there is an error, then the control immediately jumps to the CATCH block. In the CATCH block, we are rolling the transaction back. So, it's much easier to handle errors with Try/Catch construct than with @@Error system function. 2. Also notice that, in the scope of the CATCH block, there are several system functions, that are used to retrieve more information about the error that occurred These functions return NULL if they are executed outside the scope of the CATCH block. 3. TRY/CATCH cannot be used in a user-defined functions.
Comments