PL / SQL没有数据发现异常处理

时间:2017-02-14 11:02:07

标签: oracle plsql

我有一个带有列的表EMAILS:ROUTINE,EMAILS和COPIES,使用UTL_MAIL定义应向谁发送特定程序的结果(至/ cc)。

我有以下代码:

PROCEDURE myproc AS
  NO_EMAIL_FOUND EXCEPTION;
  e EMAILS%ROWTYPE;
  x NUMBER;
BEGIN

  --fetch data
  SELECT x INTO x FROM <...>;

  --fetch emails
  SELECT * INTO e FROM emails WHERE routine='FRS_WEEKLY';
  IF e.emails IS NULL AND e.copies IS NULL THEN
    RAISE NO_EMAIL_FOUND;
  END IF;

  <send mail code using UTL_MAIL>;

  EXCEPTION
    WHEN NO_EMAIL_FOUND THEN <code1>;
    WHEN NO_DATA_FOUND THEN <code2>;
    WHEN OTHERS THEN NULL; --RAISE;

END myproc;

当EMAILS表中没有电子邮件时,我希望myproc执行 code1 。我的问题是,由于在SELECT语句中引发了NO_DATA_FOUND异常,因此不会引发NO_EMAIL_FOUND异常并执行 code2 。怎么避免这个?

2 个答案:

答案 0 :(得分:0)

使用此:

PROCEDURE myproc AS
  NO_EMAIL_FOUND EXCEPTION;
  e EMAILS%ROWTYPE;
  x NUMBER;
BEGIN

  --fetch data
  SELECT x INTO x FROM <...>;

  --fetch emails
  BEGIN
    SELECT * INTO e FROM emails WHERE routine='FRS_WEEKLY';
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      RAISE NO_EMAIL_FOUND;
  END;

  IF e.emails IS NULL AND e.copies IS NULL THEN
    RAISE NO_EMAIL_FOUND;
  END IF;

  <send mail code using UTL_MAIL>;

  EXCEPTION
    WHEN NO_EMAIL_FOUND THEN <code1>;
    WHEN NO_DATA_FOUND THEN <code2>;
    WHEN OTHERS THEN NULL; --RAISE;

END myproc;

我希望您知道此例程只能处理一封电子邮件;如果有多个,则会引发TOO_MANY_ROWS异常。

答案 1 :(得分:0)

试试这个:

PROCEDURE myproc AS
    NO_EMAIL_FOUND EXCEPTION;
    e EMAILS%ROWTYPE;
    x NUMBER;
BEGIN

    BEGIN
        --fetch data
        SELECT x INTO x FROM <...>;

        --fetch emails
        BEGIN
            SELECT * INTO e FROM emails WHERE routine='FRS_WEEKLY';
        EXCEPTION WHEN NO_DATA_FOUND THEN
            RAISE NO_EMAIL_FOUND;
        END;
        IF e.emails IS NULL AND e.copies IS NULL THEN
            RAISE NO_EMAIL_FOUND;
        END IF;

        <send mail code using UTL_MAIL>;

    EXCEPTION
        WHEN NO_EMAIL_FOUND THEN <code1>;
        WHEN NO_DATA_FOUND THEN <code2>;
        WHEN OTHERS THEN NULL; --RAISE;
    END;

END myproc;