DROP PROCEDURE IF EXISTS `stp_deleteOrderTree`;


CREATE PROCEDURE `stp_deleteOrderTree`(
    IN `pOrderId` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Rimozione in unica stored di ProdItems, Righe Ordine e Ordine'
BEGIN
    -- Eliminazione production_item collegati alle order rows
    DELETE FROM production_item
    WHERE OrderRowID IN (
        SELECT  OrderRowID 
        FROM    sales_order_row 
        WHERE   OrderID = pOrderId
    );

    -- Eliminazione order rows
    DELETE 
    FROM    sales_order_row 
    WHERE   OrderID = pOrderId;

    -- Eliminazione main order
    DELETE 
    FROM    sales_order 
    WHERE   OrderID = pOrderId;

    -- Return affected rows
    SELECT ROW_COUNT() AS 'RowsDeleted';
END