RaiseError en SQL Server

RaiseError en SQL Server

Volver a: SQL Server Tutorial Para Principiantes y Profesionales

RaiseError en SQL Server con el Ejemplo

En este artículo, Voy a hablar de la RaiseError en SQL Server y junto con @@ERROR en la utilización de uno en tiempo real ejemplo. Lea nuestro artículo anterior antes de continuar con este artículo donde discutimos los conceptos básicos del manejo de excepciones en SQL Server con algunos ejemplos.,

utilice el siguiente script SQL para crear y rellenar la tabla Product y ProductSales con algunos datos de prueba.

SELECT * FROM Producto nos dará la salida debajo de la

Crear el siguiente procedimiento almacenado para la venta de productos.

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

el procedimiento almacenado anteriormente Acepta 2 parámetros: ProductID y QuantityToSell., El parámetro ProductID especifica el producto que queremos vender y el parámetro QuantityToSell especifica la cantidad que queremos vender.

el problema con el procedimiento almacenado anteriormente es que la transacción siempre se va a confirmar aunque haya un error entre actualizar la tabla de productos e insertarla en mesa de venta de productos.,

el propósito principal de envolver estas 2 declaraciones (actualizar Declaración de Producto & insertar en la declaración ProductSales) en una transacción es garantizar que ambas declaraciones se traten como una sola unidad.

Por ejemplo, si tenemos un error al ejecutar la segunda declaración, luego de la primera instrucción debe revertirse.,

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

en el procedimiento anterior, si comenta la línea (Set @MaxProductSalesId = @MaxProductSalesId + 1), y luego ejecuta el procedimiento almacenado, habrá un error de violación de clave primaria al intentar insertar en la tabla ProductSales como resultado de lo cual se revertirá toda la transacción.

Nota:

el error @@se borra y se restablece en cada ejecución de instrucción. Compruébelo inmediatamente después de la instrucción que se está verificando, o guárdelo en una variable local que se puede verificar más tarde.,

en la tabla de productos, ya tenemos un registro con ProductID = 4. Por lo tanto, la instrucción insert causa un error de violación de clave primaria. El error @ @ conserva el número de error, ya que lo estamos comprobando inmediatamente después de la instrucción que causa el error.

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

por otro lado, cuando ejecute el siguiente código, obtendrá el mensaje ‘sin errores’. Esto se debe a que el error @@se borra y se restablece en cada ejecución de la instrucción.,

en el siguiente ejemplo, estamos almacenando el valor de la función @@Error en una variable local, que luego se usa más tarde.

en el siguiente artículo, voy a discutir cómo elevar los errores explícitamente en SQL Server y también discutiremos las diferentes opciones que podemos usar con la función Raiserror. Aquí, en este artículo, trato de explicar el RaiseError en SQL Server junto con @@ERROR paso a paso con algunos ejemplos.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *