Oracle没有提出异常

时间:2018-01-31 18:34:25

标签: database oracle-sqldeveloper

所以我正在创建一个接收客户端ID和动物ID的函数,然后它需要验证该动物是否属于该客户端,如果是,它会在约会表上搜索以获取该动物的约会数量

我相信ORACLE不会提出异常......代码如下:

CREATE OR REPLACE FUNCTION CalcNrConsultas (idani IN number, idcli IN number) return number 
IS 

teste EXCEPTION;
AniNaoPertenceCli EXCEPTION;
qtd number;
t_animal Animal.IdAnimal%type;
t_cliente Animal.IDCliente%type;

BEGIN
  SELECT IDAnimal, IDCliente INTO t_animal, t_cliente FROM Animal 
  WHERE IDAnimal = idani AND IDCliente = idcli;
IF SQL%NOTFOUND THEN
    RAISE AniNaoPertenceCli;
ELSE
    SELECT COUNT(Consulta.IDAnimal) INTO qtd FROM Consulta INNER JOIN Animal ON Consulta.IdAnimal = Animal.IdAnimal
    WHERE (Consulta.IDAnimal = idani) AND (Animal.IDAnimal = idani AND Animal.IDCliente = idcli);
    IF SQL%NOTFOUND THEN
        RAISE teste;
    END IF;
END IF;
return qtd;
EXCEPTION
  WHEN AniNaoPertenceCli THEN
    dbms_output.put_line('O animal escolhido não pertence ao cliente indicado, logo não pode fazer esta consulta.');
  WHEN teste THEN 
    dbms_output.put_line('O animal indicado não efetuou nenhuma consulta.');
END;
/

1 个答案:

答案 0 :(得分:0)

问题在于你处理select查询没有结果的情况:你需要使用一个带有一些异常处理的块来捕获查询没有结果的情况。

例如,这不会捕获异常:

SQL> declare
  2      x number;
  3  begin
  4      select 1
  5      into x
  6      from dual where 1 = 2;
  7      --
  8      if sql%notfound then
  9          dbms_output.put_line('sql%notfound');
 10      end if;
 11      --
 12      dbms_output.put_line('Found');
 13  end;
 14  /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4

但这会:

SQL> declare
  2      x number;
  3  begin
  4      begin
  5          select 1
  6          into x
  7          from dual where 1 = 2;
  8      exception
  9          when NO_DATA_FOUND then
 10              x := null;
 11              dbms_output.put_line('NOT FOUND');
 12      end;
 13      --
 14      if x is not null then
 15          dbms_output.put_line('Found');
 16      end if;
 17  end;
 18  /
NOT FOUND

此外,count(...)不会提供NO_DATA_FOUND,但结果为0:

SQL> select count(1)
  2  from dual
  3  where 1 = 2;

  COUNT(1)
----------
         0

因此,要检查第二个查询的结果,您必须检查变量qtd的值。