Question

  1. I need to break out of the loop or not perform a loop when ITEM_ID is not found:

    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;
    

Also, I need to print out something like DBMS_OUTPUT.PUT_LINE('Item not found!');

Was it helpful?

Solution

There is no need to break out of the loop when an item is not found.

FOR record IN ( select-query ) LOOP statement(s) END LOOP
is a cursor FOR LOOP in Oracle terminology, here is documentation: http://docs.oracle.com/cd/E18283_01/appdev.112/e17126/cursor_for_loop_statement.htm

The cursor for loop first executes the query, then for each record returned by the query, it executes the statements between LOOP...END LOOP.

When the query renturn no rows, then the loop code is not executed at all.

If we need to detect whether the query in the cursor for loop returns rows some rows or not, then the easiest way is to declare a boolean variable and assign a value to in wihin the LOOP..END LOOP block:

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;

OTHER TIPS

Q: So then could I do it where it checks both tables? Or if the query doesn't return anything to display a message?

A: Perhaps FULL JOIN will do the trick. Try and let us know.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top