2

我对 oracle PLSQL 完全陌生。任何帮助都值得赞赏。

我在 SO 上找不到类似的问题(也许它太基础了?)

我正在运行来自 TOAD、Oracle 11G 的代码

SET SERVEROUTPUT ON
DECLARE 
var titres%ROWTYPE; 
BEGIN
    select reference, sicovam into
    var.reference, var.sicovam 
    from titres 
    where reference = '1234';
    if sql%notfound then 
        dbms_output.put_line('NOT FOUND');
    else 
        dbms_output.put_line(var.reference || '    ' ||  var.sicovam);
    end if;
END;

如果Where子句可以提取一行数据,那么它将运行该else部分

如果Where子句无法提取任何行,则会显示错误:

ORA-01403: no data found
ORA-06512: at line 4

谁能指出我正确的方向?谢谢

我尝试过使用基本的异常处理代码

When others then 
null;
end;

然后我得到另一个奇怪的结果:如果Where子句可以提取一行数据,那么它将不会运行该else部分或if部分。

4

2 回答 2

4

当 pl/sql 块内的查询没有返回任何行时,NO_DATA_FOUND立即引发异常并且块的执行将停止。所以if sql%notfound then永远不会评估条件。要捕获该异常并做出相应响应,您需要EXCEPTIONsection.

SET SERVEROUTPUT ON
DECLARE 
  var titres%ROWTYPE; 
BEGIN
    -- In this case you have to be sure that the query returns only one row
    -- otherwise the exception ORA-01422 will be raised
    select reference, sicovam into
      var.reference, var.sicovam 
     from titres 
    where reference = '1234';  

    dbms_output.put_line(var.reference || '    ' ||  var.sicovam);

EXCEPTION
  WHEN NO_DATA_FOUND 
  THEN dbms_output.put_line('NOT FOUND');    
END;
于 2013-01-08T09:51:32.090 回答
2

select into你需要使用异常NO_DATA_FOUNDTOO_MANY_ROWS

SET SERVEROUTPUT ON
DECLARE 
var titres%ROWTYPE; 
BEGIN
    select reference, sicovam into
    var.reference, var.sicovam 
    from titres 
    where reference = '1234';

    dbms_output.put_line(var.reference || '    ' ||  var.sicovam);

exception
  when no_data_found
  then
    dbms_output.put_line('NOT FOUND');
  when too_many_rows
  then
    dbms_output.put_line('2+ ROWS found');

END;
于 2013-01-08T09:51:56.293 回答