Restock Report
Write a procedure restock_report(p_supplier) that lists the products of a supplier whose units in stock are below their reorder level and that appear in at least one order not yet shipped, with the number of such orders.
Uses the Northwind sample data: load ../northwind/northwind.sql first, then run solution.sql.
Example
restock_report(1):
Products to reorder from Exotic Liquids:
Chang (17 in stock vs reorder level 25, 4 unshipped orders)
Aniseed Syrup (13 in stock vs reorder level 25, 1 unshipped orders)
Approach
Join products to their order lines and orders, filter on the supplier, UnitsInStock < ReorderLevel and ShippedDate IS NULL, and group by product to count the pending orders. The inner joins do the "at least one unshipped order" part: a product with none produces no rows.
An unknown supplier makes the first SELECT INTO fail with NO_DATA_FOUND, reported as a message instead of an error.
Lesson: procedures and exceptions.
Solutions
-- Needs the Northwind tables: run ../northwind/northwind.sql first.
SET SERVEROUTPUT ON FORMAT WRAPPED
SET FEEDBACK OFF
CREATE OR REPLACE PROCEDURE restock_report(p_supplier suppliers.SupplierID%TYPE) IS
v_name suppliers.CompanyName%TYPE;
BEGIN
SELECT CompanyName INTO v_name FROM suppliers WHERE SupplierID = p_supplier;
DBMS_OUTPUT.PUT_LINE('Products to reorder from ' || v_name || ':');
FOR p IN (
SELECT pr.ProductName, pr.UnitsInStock, pr.ReorderLevel, count(*) AS pending
FROM products pr
JOIN order_details d ON d.ProductID = pr.ProductID
JOIN orders o ON o.OrderID = d.OrderID
WHERE pr.SupplierID = p_supplier
AND pr.UnitsInStock < pr.ReorderLevel
AND o.ShippedDate IS NULL
GROUP BY pr.ProductID, pr.ProductName, pr.UnitsInStock, pr.ReorderLevel
ORDER BY pr.ProductID
) LOOP
DBMS_OUTPUT.PUT_LINE(' ' || p.ProductName || ' (' || p.UnitsInStock || ' in stock vs reorder level '
|| p.ReorderLevel || ', ' || p.pending || ' unshipped orders)');
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No supplier ' || p_supplier);
END;
/
EXEC restock_report(1)