0

I have a Procedure where I had to:

• check the quantity of the product in stock and add the requested quantity if sufficient stock is available, otherwise add the available quantity;

• fetch the current price from the products table and use that as the unit price;

• deduct the quantity ordered from the units in stock and adjust the units in stock

accordingly; and

• Contain an exception hander to handle duplicated order items. You will need to decide if this should be a CONTINUE or EXIT handler.

This is my procedure:

DROP PROCEDURE IF EXISTS sp_AddOrderItem;
DELIMITER //

CREATE PROCEDURE sp_AddOrderItem(IN orderID int, IN productID int, IN quantity smallint, IN discount float, OUT  quantityAdded int)
BEGIN 

DECLARE o_done BOOL DEFAULT FALSE;

DECLARE addQuantity INT DEFAULT 0;

DECLARE checkStock INT DEFAULT 0;

DECLARE oldStock INT DEFAULT 0;

DECLARE orderID INT DEFAULT 0;

DECLARE productID INT DEFAULT 0;

DECLARE tableName Varchar(10);

DECLARE productCurrentPrice CURSOR FOR SELECT UnitPrice FROM Products WHERE     ProductID = productID ;

DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered';

SET checkStock = (SELECT UnitsInStock FROM Products WHERE Products.ProductID = productID LIMIT 1);
SET oldStock = (SELECT Quantity FROM Order_Details WHERE OrderID = orderID AND ProductID = productID LIMIT 1);
SET orderID = (SELECT OrderId, ProductId FROM Order_Details WHERE ProductID = productID LIMIT 1);

IF checkStock >= quantity THEN

    SET addQuantity = oldStock + quantity;
    SET checkStock = oldStock - quantity;

    ELSE
        SET addQuantity = oldStock + checkStock;
        SET checkStock = 0;
        SET SQL_SAFE_UPDATES = 0;
        UPDATE IGNORE Order_Details SET Quantity = addQuantity WHERE OrderID = orderID AND ProductID = productID;
        UPDATE IGNORE Products SET UnitsInStock = checkStock WHERE ProductID = productID;

        SELECT orderID, productID, quantity, addQuantity, oldStock, checkStock;

END IF;

OPEN productCurrentPrice;
FETCH productCurrentPrice INTO orderDetailPrice;
CLOSE productCurrentPrice;

END // 
DELIMITER ;

AND THIS IS WHAT I GET : Error Code: 1062. Duplicate entry '2018-11-17 20:27:14' for key 'PRIMARY'

0 Answers0