我有3张桌子
项目: Item_Number PK ,Item_Name,Current_Price,Production_cost。
成分: Ingredient_Number PK ,Ingredient_Name,Ingredient_Cost
Item_Ingredient: Item_Number PK / FK,Ingredient_Number PK / FK ,Quantity_Needed
1项目由3或4种不同成分制成。 每个项目的Production_Cost由所有的总和(ingredient_Cost * Quantity_Needed)计算。 我试图用光标创建过程,如果生产成本<生产成本<<生产成本<所有的总和(ingredient_Cost * Quantity_Needed)。但我不知道如何在我的程序中计算。 你能帮帮我解决一下吗?这是我的代码的第一部分:
CREATE OR REPLACE PROCEDURE PR_Check_Cost
AUTHID CURRENT USER
IS
V_Production_Cost item.Production_cost%Type;
V_New_Production_Cost number (6,2);
V_Item_Number number (5,0);
Cursor C_Cost IS
select ii.item_number, SUM(in.ingredient_cost * ii.quantity_Needed)
from item.ingredient ii, ingredient in
where ii.ingredient_number = in_ingredient_number
group by ii.item_number
Begin
Open C_Cost;
Fetch C_Cost into V_Item_Number, V_New_Production_Cost;
While C_Product_Cost%FOUND LOOP
select Production_Cost
into V_Production_Cost
From Item
Where Item_Number = V_Item_Number;
If V_Production_Cost < V_New_Production_Cost THEN
UPDATE Item
Set Production_Cost = V_New_Production_Cost
Where Item_Number = V_Item_Number;
End If;
Fetch C_Cost into V_Item_Number, V_New_Production_Cost;
End loop;
Close C_Cost;
End PR_Check_cost;/
SHOW ERRORS;
答案 0 :(得分:1)
你可以用一个UPDATE语句完成它,如下所示:
UPDATE item
SET production_cost = (SELECT SUM(t2.ingredient_cost * t1.quantity_needed)
FROM item_ingredient t1 JOIN ingredient t2 ON t1.ingredient_number = t2.ingredient_number
WHERE t1.item_number = item.item_number)
WHERE production_cost < (SELECT SUM(t2.ingredient_cost * t1.quantity_needed)
FROM item_ingredient t1 JOIN ingredient t2 ON t1.ingredient_number = t2.ingredient_number
WHERE t1.item_number = item.item_number);
我不知道你是想完成它还是学习游标和程序,在这种情况下,你可以使用这样的程序(但这样效率很低):
CREATE OR REPLACE PROCEDURE pr_check_cost AUTHID CURRENT USER IS
v_production_cost item.production_cost%TYPE;
CURSOR c_cost IS
SELECT it.item_number, SUM(in.ingredient_cost * it.quantity_needed) production_cost
FROM item_ingredient it, ingredient in
WHERE it.ingredient_number = in.ingredient_number
GROUP BY it.item_number;
BEGIN
FOR r IN c_cost LOOP
SELECT production_cost
INTO v_production_cost
FROM item
WHERE item_number = r.item_number;
IF v_production_cost < r.production_cost THEN
UPDATE item
SET production_cost = r.production_cost
WHERE item_number = r.item_number;
END IF;
END LOOP;
COMMIT;
END pr_check_cost;
请注意,我还没有编译代码,但可能会有一些错误。
答案 1 :(得分:0)
我认为您的代码对于您要实现的目标来说有点过于复杂。 更好,更简单的方法IMO是运行整个项目表的游标,然后为每个项目运行此查询,将其结果与当前生产成本进行比较 -
select sum(total_ing_cost)
into calc_cost
from (
select (d.ingredient_cost * q.quantity_needed) as total_ing_cost
from item i, ingredient d, item_ingredient q
where i.item_number = q.item_number
and d.ingredient_number = q.ingredient_number
and item_number = current_item_in_cursor
)
我还没有在这个工作站上安装Oracle,所以查询的语法可能不完全正确,但我们欢迎您使用它。