我正在使用以下查询来查找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在几年中的返回值?
答案 0 :(得分:2)
可能最好的方法是将出生日期选择为局部变量,然后对其进行测试:
...
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
....
答案 1 :(得分:1)
在Oracle中使用空值时需要小心。
Oracle中永远不会出现以下情况:
if years = null then
你应该使用这个:
if years is null then
考虑以下情况:
if years = 0 then
yrs_string := 'less than a yr';
elsif years is not null then
yrs_string := years || 'years';
else
yrs_string := 'N/A'
end if;