Error handling in sql server
Syntax:
BEGIN TRY { Any set of SQL statements } END TRY BEGIN CATCH [ Optional: Any set of SQL statements ] END CATCH [Optional: Any other SQL Statements]
Error handling in sql server Syntax:
In procedure spSellProduct, 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.
Create Procedure spSellProduct @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 Try Begin Transaction -- 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) Commit Transaction End Try Begin Catch Rollback Transaction Select ERROR_NUMBER() as ErrorNumber, ERROR_MESSAGE() as ErrorMessage, ERROR_PROCEDURE() as ErrorProcedure, ERROR_STATE() as ErrorState, ERROR_SEVERITY() as ErrorSeverity, ERROR_LINE() as ErrorLine End Catch End End