在Oracle PL/SQL中不打印输出

hrirmatl  于 2022-10-04  发布在  Oracle
关注(0)|答案(1)|浏览(509)

我是甲骨文的新手。我编写了一个简单的PL/SQL来将SNAPID存储到变量中并打印SNAPID。如果我使用空值的异常处理,那么即使有一些来自SQL查询的值,输出也不会打印。如果我删除了异常块,则会正确打印结果。为什么不采用异常块?代码中应该添加什么?提前谢谢!

Oracle数据库版本:19.3.0.0.0 RU

例外:

set serveroutput on
DECLARE
snap number;
BEGIN
select max(dhsq.snap_id) into snap
        from dba_hist_sqlstat dhsq
        inner join dba_hist_snapshot dhss on (dhss.snap_id = dhsq.snap_id)
        where dhsq.sql_id='38mkqq9vpu6vf';
DBMS_OUTPUT.PUT_LINE(snap);
EXCEPTION
  WHEN NO_DATA_FOUND THEN
  snap := NULL;
END;
/
  2    3    4    5    6    7    8    9   10   11   12   13
PL/SQL procedure successfully completed.

输出无异常:

set serveroutput on
DECLARE
snap number;
BEGIN
select max(dhsq.snap_id) into snap
        from dba_hist_sqlstat dhsq
        inner join dba_hist_snapshot dhss on (dhss.snap_id = dhsq.snap_id)
        where dhsq.sql_id='38mkqq9vpu6vf';
DBMS_OUTPUT.PUT_LINE(snap);  2    3    4    5    6    7    8
  9  END;
 10  /
743 <========
PL/SQL procedure successfully completed.

以下输出为静态输出,将保留7天。因此,此SQL_id保存在磁盘中,不会返回零行。

select max(dhsq.snap_id) from dba_hist_sqlstat dhsq inner join dba_hist_snapshot dhss on (dhss.snap_id = dhsq.snap_id) where dhsq.sql_id='38mkqq9vpu6vf';

MAX(DHSQ.SNAP_ID)
-----------------
              743
hgc7kmma

hgc7kmma1#

这里一定还有其他原因,因为选择变量的最大值永远不会引发NO_DATA_FOUND。如果没有行,它将返回NULL。这意味着异常在问题中的代码中是不相关的。有没有它在代码中-不会改变任何事情。
示例:

SET SERVEROUTPUT ON
DECLARE
    snap        Number;
    null_snap   Number;
BEGIN
    Select
        Nvl(Max(NUM), 0),
        Max(NUM) 
    InTo null_snap, snap
    From 
        (Select 'A' "LETTER", 99 "NUM" From Dual)
    Where 
        LETTER = 'B';
    DBMS_OUTPUT.PUT_LINE('NULL_SNAP = ' || To_Char(null_snap) || '***');
    DBMS_OUTPUT.PUT_LINE('SNAP = ' || To_Char(snap) || '***');
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        snap := NULL;
        DBMS_OUTPUT.PUT_LINE('ERR - ' || SQLERRM);
END;
--  anonymous block completed
--  NULL_SNAP = 0***
--  SNAP =***

很明显,没有与WHERE条件匹配的行,并且Max(NUM)返回Null,并使用NVL()函数将其更改为0。
如果有不同的SELECT INTO-没有像这样的max函数

...
Select
    NUM 
InTo snap
...

则将引发异常,并且上面的代码将产生

--  anonymous block completed
--  ERR - ORA-01403: no data found

最后,如果至少有一行,则如下所示

...
Select
        Nvl(Max(NUM), 0),
        Max(NUM) 
    InTo null_snap, snap
    From 
        (Select 'A' "LETTER", 99 "NUM" From Dual)
    Where 
        LETTER = 'A';
...

结果为

anonymous block completed
NULL_SNAP = 99***
SNAP = 99***

您的代码在这里运行得很好,不管有没有异常...致敬..。

相关问题