DROP PROCEDURE IF EXISTS get_invoice;
DELIMITER $$
CREATE PROCEDURE get_invoice (IN pMonth INT, IN pYear INT)
BEGIN
DECLARE recordCount INT;
DECLARE isEndOfCursor BOOLEAN DEFAULT FALSE;
DECLARE quantitySold INT DEFAULT 0;
DECLARE itemPrice FLOAT DEFAULT 0;
DECLARE totalRevenue FLOAT DEFAULT 0;
DECLARE cur CURSOR FOR
SELECT A.quantity, A.price
FROM items_sold A
INNER JOIN sales_notes B
ON A.sale_number = B.number
WHERE MONTH(B.sale_date) = pMonth AND YEAR(B.sale_date) = pYear;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET isEndOfCursor = TRUE;
SET recordCount = (SELECT COUNT(*) FROM sales_notes
WHERE MONTH(sale_date) = pMonth AND YEAR(sale_date) = pYear);
IF recordCount > 0 THEN
OPEN cur;
WHILE (isEndOfCursor = FALSE) DO
FETCH cur INTO quantitySold, itemPrice;
IF (isEndOfCursor IS FALSE) THEN
SET totalRevenue = totalRevenue + (quantitySold * itemPrice);
END IF;
END WHILE;
CLOSE cur;
SELECT CONCAT('Total Revenue for ', pMonth, ' ', pYear, ': $', totalRevenue) AS Total_Revenue;
ELSE
SELECT 'No records found for the specified month and year.' AS Message;
END IF;
END $$
DELIMITER ;
CALL get_invoice(09, 2023);