1. 程式人生 > >oracle儲存過程的遞迴呼叫

oracle儲存過程的遞迴呼叫



心裡知道有這麼回事,但很少在實踐中用到,下面是一個查詢父地址的過程。

CREATE OR REPLACE FUNCTION F_CALLPARENTARDADDRESS(V_ARDADDRESSID IN NUMBER,
                                                      V_GRADE     IN NUMBER)
  RETURN NUMBER IS
  V_SELFGRADE         NUMBER;
  V_PARENT_GRADE      NUMBER;
  V_PARENT_ADDRESSID  NUMBER;
BEGIN
  BEGIN
    SELECT TELEARDADDRESS.GRADE, PARENTADDRESS.GRADE, PARENTADDRESS.ID
      INTO V_SELFGRADE, V_PARENT_GRADE, V_PARENT_ADDRESSID
      FROM TELEARDADDRESS, TELEARDADDRESS PARENTADDRESS
     WHERE TELEARDADDRESS.ID = V_ARDADDRESSID
       AND TELEARDADDRESS.PARENTADDRESSID = PARENTADDRESS.ID(+);
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      RETURN 0;
  END;
  IF V_GRADE = V_SELFGRADE THEN
    RETURN V_ARDADDRESSID;
  ELSIF (V_PARENT_GRADE IS NULL) OR (V_PARENT_ADDRESSID IS NULL) OR
        (V_GRADE > V_PARENT_GRADE) THEN
    RETURN 0;
  ELSIF (V_GRADE = V_PARENT_GRADE) THEN
    RETURN V_PARENT_ADDRESSID;
    --遞迴呼叫
  ELSE
    RETURN F_CALLPARENTARDADDRESS(V_PARENT_ADDRESSID, V_GRADE);
  END IF;
END F_CALLPARENTARDADDRESS;