2013-04-27 86 views
0

我有3個表:SELECT INTO返回多於1行 - ORA-01422

products (prod_id, prod_name, prod_sale_price), order_details (order_id, prod_id, prod_quantity) 

orders (order_id, order_date, cust_id, emp, id)
基本上我試圖創建一個函數,當輸入order_id時獲得總訂單成本,但是我在嘗試將其放入代碼時遇到問題。
特別試圖將每個產品放入一個單獨的變量中。

CREATE OR REPLACE FUNCTION TotalOrderCost (input_id IN NUMBER) 
RETURN NUMBER 
IS 

    given_id NUMBER := input_id; 
    prod_count NUMBER; 
    prod_id NUMBER; 
    prod_price_by_quantity NUMBER := 0; 
    total_order_cost NUMBER := 0; 

BEGIN 

    SELECT COUNT(prod_id) 
    INTO prod_count 
    FROM order_details 
    WHERE order_id = given_id; 

    FOR i IN 1..prod_count 
     LOOP 

      /* select into that returns more then 1 row when there is more than one product in the order*/ 
      SELECT prod_sale_price*prod_quantity 
      INTO prod_price_by_quantity 
      FROM order_details od 
       JOIN products p 
        ON od.prod_id = p.prod_id 
      WHERE order_id = given_id; 

      total_order_cost := total_order_cost + prod_price_by_quantity; 

     END LOOP; 

    RETURN total_order_cost; 

END TotalOrderCost; 
/
+0

你的意思是你只是想選擇總和(prod_sale_price * prod_quantity'?你不需要循環,這只是意味着你計算相同的值多少次,並將它們加在一起,這會給出太高總之,我不知道我是否錯過了某些東西,但是...? – 2013-04-27 12:02:28

+0

你已經得到了它,雖然我不得不循環,因爲訂單中有多種產品,但是效果很好。 – Michael 2013-04-27 20:00:00

回答

1

這聽起來像你只是想要一個SUM

SELECT SUM(prod_sale_price*prod_quantity) 
    INTO total_order_cost 
    FROM order_details od 
    JOIN products p 
     ON od.prod_id = p.prod_id 
WHERE order_id = given_id; 

雖然目前沒有出現任何需要做的COUNT或引入循環。

+0

這正是我想要做的,非常感謝您的幫助。 – Michael 2013-04-27 19:51:38