在pl SQL循环中if / else

时间:2015-09-06 03:05:18

标签: sql oracle loops if-statement

我正在尝试使用IF.. ELSE条件和对帐单更新库存单位,但我在尝试运行时遇到错误:

PLS-00103: Encountered the symbol "LOOP" when expecting one of the following:
    if

下面的代码,我在循环中运行它以吐出所有数据,直到它用完为止:

DECLARE

--Declare cursor
 CURSOR part_cur
 IS 
 SELECT PARTNUMBER, PARTDESC, ITEMCLASS, UNITSONHAND, UNITSONHAND
 FROM PART
 ORDER BY UPPER(PARTNUMBER);

--Declare variables
 v_PartNumber PART.PARTNUMBER%TYPE;
 v_PartDesc PART.PARTDESC%TYPE;
 v_ItemClass PART.ITEMCLASS%TYPE;
 v_UnitsOnHand PART.UNITSONHAND%TYPE;
 v_nUnitsOnHand PART.UNITSONHAND%TYPE;

BEGIN
 OPEN part_cur;
 LOOP

--Initialise variables
  FETCH part_cur INTO v_PartNumber, v_PartDesc, v_ItemClass, v_UnitsOnHand, v_nUnitsOnHand;
        EXIT WHEN part_cur%NOTFOUND;

--Perform Calculations
    IF ITEMCLASS = 'AO' AND UNITSONHAND <20 THEN v_nUnitsOnHand := UNITSONHAND + 5;
ELSE IF ITEMCLASS = 'AO' AND UNITSONHAND <100 THEN v_nUnitsOnHand := UNITSONHAND + 10;
ELSE IF ITEMCLASS = 'AO' AND UNITSONHAND >=100 THEN v_nUnitsOnHand := UNITSONHAND + 25;
END IF;

--Format for output

--Output results
        DBMS_OUTPUT.PUT_LINE('Part ' || UPPER(v_PartNumber) || ' - ' || INITCAP(v_PartDesc) || ' of item class ' || UPPER(v_ItemClass) || ' had a total of ' || v_UnitsOnHand || ' units on hand, 
        and now has ' || v_nUnitsOnHand || ' units on hand after the database was updated.
        ');
 END LOOP;
 CLOSE part_cur;
END;

非常感谢任何帮助或指示,谢谢。

2 个答案:

答案 0 :(得分:3)

您的IF声明目前如下所示:

IF ITEMCLASS = 'AO' AND UNITSONHAND <20 THEN
    v_nUnitsOnHand := UNITSONHAND + 5;
ELSE
    IF ITEMCLASS = 'AO' AND UNITSONHAND <100 THEN
        v_nUnitsOnHand := UNITSONHAND + 10;
    ELSE
        IF ITEMCLASS = 'AO' AND UNITSONHAND >=100 THEN
            v_nUnitsOnHand := UNITSONHAND + 25;
        END IF;

所以它缺少两个END IF。因此,当Oracle看到END LOOP时,会抱怨,因为它预计会END IF

要解决此问题,只需将ELSE IF替换为ELSIF,这是一个特殊的关键字,用于此目的:

IF ITEMCLASS = 'AO' AND UNITSONHAND <20 THEN
    v_nUnitsOnHand := UNITSONHAND + 5;
ELSIF ITEMCLASS = 'AO' AND UNITSONHAND <100 THEN
    v_nUnitsOnHand := UNITSONHAND + 10;
ELSIF ITEMCLASS = 'AO' AND UNITSONHAND >=100 THEN
    v_nUnitsOnHand := UNITSONHAND + 25;
END IF;

答案 1 :(得分:-1)

试试这个:

FOR record_var in part_cur
LOOP
   {...statements...}
END LOOP;

之后你可以写:

record_var.v_PartNumber, etc

用于访问这些字段。