首页 > 解决方案 > 用于检查不确定值的 PL/SQL 构造

问题描述

我正在使用以下查询来查找 PL/SQL 过程中年月两个日期的差异:-

  ...   
  years number;
  months number ;
  yrs_string varchar2;
  months_string varchar2;
  begin
  ...      
  select trunc(months_between(sysdate,date_of_birth)/12) into years,
  months_between(sysdate,date_of_birth) -  
  12*trunc(months_between(sysdate,date_of_birth)/12) into months from   
  tbl_student where student id = incoming_id;
  ---test 1
         if years = 0 then
            yrs_string := 'N/A or less than a yr";
         else
            yrs_string := years || 'years';
         end if;
   --- test 2
          if years = null then
              ....

但是,如果 date_of_birth 未在表中输入,则测试 1 和测试 2 均失败。如果用户未输入 date_of_birth,如何检查年份值或 PL/SQL 返回的年份?

标签: oracleif-statementplsqlnull

解决方案


可能最好的方法是将出生日期选择为局部变量,然后对此进行测试:

...   
  l_dob date;
  years number;
  months number ;
  yrs_string varchar2;
  months_string varchar2;
  begin
  ...      
  select date_of_birth into l_dob
  from tbl_student 
  where student id = incoming_id;

  -- new test

  if l_dob is null then
       yrs_string := 'Date of birth is null';
  else
      years := trunc(months_between(sysdate, l_dob)/12);
      months := months_between(sysdate, l_dob) -  12*trunc(months_between(sysdate, l_dob)/12);
  ---test 1
         if years = 0 then
            yrs_string := 'N/A or less than a yr";
         else
            yrs_string := years || 'years';
         end if;
   --- test 2
          if years is null then
              ....

推荐阅读