如何获取PL / SQL关联数组DS的NULL条件检查

时间:2013-10-04 15:07:50

标签: sql oracle plsql

我有以下代码片段,我想知道如何检查关联数组中是否存在条目

set serveroutput on;
DECLARE
    TYPE per_form_metric IS record
      (
              output_achieved_itd NUMBER,
              output_achieved_ptd NUMBER
      );
      TYPE per_form_metrics_tbl IS TABLE OF per_form_metric INDEX BY VARCHAR2(10) ;
      TYPE interval_number_tbl IS TABLE OF per_form_metrics_tbl INDEX BY VARCHAR2(10) ;
      TYPE ms_output_tbl IS TABLE OF interval_number_tbl INDEX BY VARCHAR2(100) ;
      g_ms_output_tbl ms_output_tbl ;

      l_per_f_rec        per_form_metric;
      l_per_f_tbl        per_form_metrics_tbl;
      l_per_int_tbl     interval_number_tbl;
      l_ms_out_tbl    ms_output_tbl;

 BEGIN
    l_per_f_rec.output_achieved_itd := 1000;
    l_per_f_rec.output_achieved_ptd := 1000;

    l_per_f_tbl('Period 1') := l_per_f_rec;

    l_per_int_tbl('Interval 1') := l_per_f_tbl;

    l_ms_out_tbl('1') := l_per_int_tbl;

    -- Now get me the output_achieved_itd for 1 , Interval 1, Period 1

    dbms_output.put_line(l_ms_out_tbl('1')('Interval 1')('Period 1').output_achieved_itd);

    dbms_output.put_line(l_ms_out_tbl('2')('Interval 1')('Period 1').output_achieved_itd);


END;

此代码的输出如下

Error report:
ORA-01403: no data found
ORA-06512: at line 31
01403. 00000 -  "no data found"
*Cause:    
*Action:
1000

如何检查

l_ms_out_tbl('2')('Interval 1')('Period 1').output_achieved_itd 

存在?

我想说点什么

IF (l_ms_out_tbl('2')('Interval 1')('Period 1').output_achieved_itd IS NOT NULL) THEN
    do something awesome
  ELSE 
    continue wallowing
  END IF;

2 个答案:

答案 0 :(得分:6)

不是评估nullality,而是评估存在:

IF (l_ms_out_tbl.EXISTS('2'))
THEN
   IF (l_ms_out_tbl('2').EXISTS('Interval 1'))
   THEN
      IF (l_ms_out_tbl('2')('Interval 1').EXISTS('Period 1'))
      THEN
         null; --do something awesome
      END IF;
   END IF;
ELSE 
    null; --continue wallowing
END IF;

或捕获NO_DATA_FOUND:

begin
   dbms_output.put_line(l_ms_out_tbl('2')('Interval 1')('Period 1').output_achieved_itd)
   -- did something awesome
exception
   when NO_DATA_FOUND then
      null;
      -- continue wallowing
end;

答案 1 :(得分:2)

使用exists收集方法。 E.g:

declare
  type foo_t is table of varchar2(20) index by varchar2(20);
  v_foos foo_t;
begin
  v_foos('FOO') := 'this is foo';

  if v_foos.exists('FOO') then
    dbms_output.put_line('exists');
  else
    dbms_output.put_line('not exists');
  end if;
end;
/

如何将它应用于嵌套的关联数组留给OP:)

另见: