我正在努力使这项工作,但无论我做什么,od_total var总是空的。我无法让它发挥作用。
我正在尝试运行游标来获取ordersid列表并将其保存到每个循环的o_id中。然后,我使用第二个游标使用存储在o_id中的值来执行另一个查询,将结果存储到od_total中。虽然o_id似乎存储了值,但od_total由于某种原因始终是空的。
CREATE OR REPLACE PROCEDURE p_practicum2_practice IS
o_id CHAR(5);
od_total NUMBER := 0;
CURSOR ordersid IS
SELECT DISTINCT orderdetails.orderid FROM orderdetails
INNER JOIN orders ON orderdetails.orderid = orders.orderid
INNER JOIN customers ON orders.customerid = customers.customerid
WHERE orders.customerid = 'LILAS';
CURSOR total IS
SELECT SUM(unitprice*quantity) FROM orderdetails WHERE orderid = o_id;
BEGIN
OPEN ordersid;
OPEN total;
LOOP
FETCH ordersid INTO o_id;
EXIT WHEN ordersid%notfound;
LOOP
FETCH total INTO od_total;
EXIT WHEN total%notfound;
END LOOP;
dbms_output.put_line(o_id || ' ---- ' || od_total);
END LOOP;
CLOSE ordersid;
CLOSE total;
END;
这就是我得到的结果: enter image description here
答案 0 :(得分:0)
到目前为止,我可以理解您的问题,您希望为从游标od_total
传递的所有od_id
显示ordersid
。你没有得到任何东西,因为od_id
没有传递给你的第二个光标。阅读下面的代码内联注释如何将参数传递给游标。
CREATE OR REPLACE PROCEDURE p_practicum2_practice
IS
o_id CHAR(5);
od_total NUMBER := 0;
CURSOR ordersid
IS
SELECT DISTINCT orderdetails.orderid
FROM orderdetails
INNER JOIN orders
ON orderdetails.orderid = orders.orderid
INNER JOIN customers
ON orders.customerid = customers.customerid
WHERE orders.customerid = 'LILAS';
CURSOR total(v_oid char)
IS
SELECT SUM(unitprice*quantity)
FROM orderdetails
WHERE orderid = v_oid;
BEGIN
OPEN ordersid;
LOOP
FETCH ordersid INTO o_id;
EXIT WHEN ordersid%notfound;
OPEN total(o_id); --<--This is how you pass the paramater to your cursor
LOOP
FETCH total INTO od_total;
EXIT WHEN total%notfound;
dbms_output.put_line(o_id || ' ---- ' || od_total);
END LOOP;
CLOSE total;
--If you print here then only the last od_total value will be printed.
--dbms_output.put_line(o_id || ' ---- ' || od_total);
END LOOP;
CLOSE ordersid;
END;
输出:
17465 ---- 6
12345 ---- 3
14435 ---- 4
19045 ---- 6
19345 ---- 8