当找不到ITEM_ID时,我需要突破循环或不执行循环:
BEGIN
FOR item IN(SELECT ITEM.ITEM_ID,
ITEM.ITEM_DESC,
INVENTORY.INV_PRICE
FROM ITEM
INNER JOIN INVENTORY
ON ITEM.ITEM_ID = INVENTORY.ITEM_ID
WHERE ITEM.ITEM_ID = '1'
ORDER BY ITEM.ITEM_ID,
INVENTORY.INV_PRICE)
LOOP
DBMS_OUTPUT.PUT_LINE(
item.ITEM_ID||' '||item.ITEM_DESC||' ' ||item.INV_PRICE);
END LOOP;
END;
另外,我需要打印出类似DBMS_OUTPUT.PUT_LINE('Item not found!');
答案 0 :(得分:1)
无需break out of the loop when an item is not found
。
FOR record IN ( select-query ) LOOP statement(s) END LOOP
在Oracle术语中是游标FOR LOOP ,这里是文档:http://docs.oracle.com/cd/E18283_01/appdev.112/e17126/cursor_for_loop_statement.htm
循环游标首先执行查询,然后对查询返回的每条记录执行LOOP ... END LOOP之间的语句。
当查询没有行时,则根本不执行循环代码。
如果我们需要检测游标for循环中的查询是否返回行某些行,那么最简单的方法是声明一个布尔变量并为LOOP..END LOOP块分配一个值:
DECLARE
rows_found BOOLEAN := false;
BEGIN
FOR record IN ( select-query )
LOOP
rows_found := true;
... do something else ....
END LOOP:
IF NOT rows_found THEN
DBMS_OUTPUT.PUT_LINE('Item not found!');
END IF;
END;
答案 1 :(得分:0)
答:也许FULL JOIN会做到这一点。试着告诉我们。
BEGIN
FOR item IN(SELECT ITEM.ITEM_ID,
ITEM.ITEM_DESC,
INVENTORY.INV_PRICE
FROM ITEM
FULL JOIN INVENTORY
ON ITEM.ITEM_ID = INVENTORY.ITEM_ID
WHERE ITEM.ITEM_ID = '1')
LOOP
IF ITEM.ITEM_ID IS NULL OR INVENTORY.ITEM_ID IS NULL THEN
EXIT;
ELSE
DBMS_OUTPUT.PUT_LINE(item.ITEM_ID||' '||item.ITEM_DESC||' ' ||item.INV_PRICE);
END IF;
END LOOP;
-- in PLSQL if query doesn’t return anything exception is raised
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO_DATA_FOUND');
END;