$ cat sql/getRecipeCost.sql
DROP PROCEDURE IF EXISTS getRecipeCost;
DELIMITER //
CREATE PROCEDURE getRecipeCost(id INT(10) unsigned, OUT cost DECIMAL(6,3) unsigned)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE ingredientSku MEDIUMINT(8) unsigned;
DECLARE ingredientQty DECIMAL(8,2) unsigned;
DECLARE ingredientCost DECIMAL(6,3);
DECLARE ingredientRecipeId INT(10) unsigned;
DECLARE myCursor CURSOR FOR
SELECT sku,qty FROM recipes_data WHERE recipeid=id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
IF ISNULL(cost) THEN
SET cost=0;
END IF;
OPEN myCursor;
myLoop: LOOP
FETCH myCursor INTO ingredientSku,ingredientQty;
IF done=1 THEN LEAVE myLoop; END IF;
SELECT recipe_cost FROM vendors_products WHERE sku=ingredientSku
INTO ingredientCost;
IF ingredientCost=0 THEN
SELECT recipeid FROM recipes WHERE sku=ingredientSku
INTO ingredientRecipeId;
call getRecipeCost(ingredientRecipeId, cost);
ELSEIF ingredientCost != 0 THEN
SET cost = cost + ingredientCost;
END IF;
END LOOP myLoop;
SELECT cost;
END;
//
DELIMITER ;