RaiseError in SQL Server

RaiseError in SQL Server

Terug naar: SQL Server Tutorial Voor Beginners en Professionals

RaiseError in SQL Server met Voorbeeld

In dit artikel, Ik ben dan ook van plan om te discussiëren over de RaiseError in SQL Server en samen met @@FOUT bij het gebruik van een real-time voorbeeld. Lees ons vorige artikel alvorens verder te gaan naar dit artikel waar we de basisprincipes van de afhandeling van uitzonderingen in SQL Server bespraken met enkele voorbeelden.,

gebruik het onderstaande SQL-Script om de tabel Product en productverkoop te maken en te vullen met enkele testgegevens.

SELECT * FROM Product will give us the below output

creëer de volgende opgeslagen procedure voor de verkoop van producten.

CREATE PROCEDURE spSellProduct@ProductID INT,@QuantityToSell INTASBEGIN -- First we need to Check the stock available for the product we want to sell DECLARE @StockAvailable INT SELECT @StockAvailable = QuantityAvailable FROM Product WHERE ProductId = @ProductId -- We need to throw an error to the calling application -- if the stock is less than the quantity we want to sell IF(@StockAvailable< @QuantityToSell) BEGIN Raiserror('Enough Stock is not available',16,1) END -- If enough stock is available ELSE BEGIN -- We need to start the transaction BEGIN TRANSACTION -- First we need to reduce the quantity available UPDATEProduct SET QuantityAvailable = (QuantityAvailable - @QuantityToSell) WHEREProductID = @ProductID -- Calculate MAX ProductSalesId DECLARE @MaxProductSalesId INT SELECT@MaxProductSalesId = CASE WHEN MAX(ProductSalesId) IS NULL THEN 0 ELSE MAX(ProductSalesId) END FROM ProductSales-- Increment @MaxProductSalesId by 1, so we don't get a primary key violationSet @MaxProductSalesId = @MaxProductSalesId + 1 -- We need to insert the quantity sold into the ProductSales table INSERT INTO ProductSales(ProductSalesId, ProductId, QuantitySold) VALUES(@MaxProductSalesId, @ProductId, @QuantityToSell) COMMIT TRANSACTION EndEND

de hierboven opgeslagen procedure accepteert 2 parameters-ProductID en QuantityToSell., De productId parameter specificeert het product dat we willen verkopen en de QuantityToSell parameter specificeert de hoeveelheid die we willen verkopen.

het probleem met de hierboven opgeslagen procedure is dat de transactie altijd zal worden vastgelegd, ook al is er ergens een fout tussen het bijwerken van de producttabel en het invoegen ervan in de productsales-tabel.,

het belangrijkste doel van het verpakken van deze 2 verklaringen (Update Product Statement & Insert into Product Sales statement) in een transactie is ervoor te zorgen dat beide verklaringen worden behandeld als één eenheid.

bijvoorbeeld, als we een fout hebben bij het uitvoeren van de tweede statement, dan moet de eerste statement worden teruggedraaid.,

ALTER PROCEDURE spSellProduct@ProductID INT,@QuantityToSell INTASBEGIN -- First we need to Check the stock available for the product we want to sell DECLARE @StockAvailable INT SELECT @StockAvailable = QuantityAvailable FROM Product WHERE ProductId = @ProductId -- We need to throw an error to the calling application -- if the stock is less than the quantity we want to sell IF(@StockAvailable< @QuantityToSell) BEGIN Raiserror('Enough Stock is not available',16,1) END -- If enough stock is available ELSE BEGIN -- We need to start the transaction BEGIN TRANSACTION -- First we need to reduce the quantity available UPDATEProduct SET QuantityAvailable = (QuantityAvailable - @QuantityToSell) WHEREProductID = @ProductID -- Calculate MAX ProductSalesId DECLARE @MaxProductSalesId INT SELECT@MaxProductSalesId = CASE WHEN MAX(ProductSalesId) IS NULL THEN 0 ELSE MAX(ProductSalesId) END FROM ProductSales-- Increment @MaxProductSalesId by 1, so we don't get a primary key violationSet @MaxProductSalesId = @MaxProductSalesId + 1 -- We need to insert the quantity sold into the ProductSales table INSERT INTO ProductSales(ProductSalesId, ProductId, QuantitySold) VALUES(@MaxProductSalesId, @ProductId, @QuantityToSell) -- The @@Error returns a NON-ZERO value if there is an error, otherwise it will return ZERO, -- indicating that the previous SQL statement encountered no errors IF(@@ERROR <> 0) BEGIN ROLLBACK TRANSACTION PRINT 'Rolled Back the Transaction' END ELSE BEGIN COMMIT TRANSACTION PRINT 'Committed the Transaction' END EndEND

in de bovenstaande procedure, als u de regel becommentarieert (Set @MaxProductSalesId = @MaxProductSalesId + 1), en vervolgens de opgeslagen procedure uitvoert, zal er een fout optreden bij het invoegen van een primaire sleutel in de tabel met productverkoop, waardoor de hele transactie wordt teruggedraaid.

opmerking:

de @@ – fout wordt gewist en gereset bij elke uitvoering van een statement. Controleer het onmiddellijk na het statement dat wordt geverifieerd, of sla het op in een lokale variabele die later kan worden gecontroleerd.,

in de producttabel hebben we al een record met ProductID = 4. Dus het insert statement veroorzaakt een fout in primaire sleutelovertreding. De @ @ ERROR behoudt het foutnummer, zoals we controleren voor het onmiddellijk na de verklaring die de fout veroorzaakt.

INSERT INTO Product values(4, 'Mobile Phone', 1500, 100)IF(@@ERROR <> 0) PRINT 'Error Occurred'ELSE PRINT 'No Errors'

aan de andere kant, wanneer u de onderstaande code uitvoert, krijgt u het bericht ‘Geen fouten’. Dit komt omdat de @@fout wordt gewist en gereset op elke uitvoering van het statement.,

in het onderstaande voorbeeld slaan we de waarde van de @@Error-functie op in een lokale variabele, die later wordt gebruikt.

In het volgende artikel ga ik bespreken hoe je expliciet fouten kunt maken in SQL Server en we zullen ook de verschillende opties bespreken die we kunnen gebruiken met de raiserror-functie. Hier, in dit artikel, probeer ik de RaiseError in SQL Server samen met @@ERROR stap voor stap uit te leggen met enkele voorbeelden.

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *