Oracle和SQL Server - 将date与null进行比较时的结果不同

时间:2015-12-01 10:28:52

标签: sql-server oracle date jpql

我在JPQL中有以下查询:

select * 
from Record rec 
where rec.validFrom <= :param 
and (rec.validTo is null or rec.validTo >= :param)

我知道,数据库中只存在一条记录。如果我用param = null运行它,在Oracle上我得到了记录。但是,如果我在SQL Server数据库上运行它,我不会得到记录。对我而言,只有可疑部分是rec.validFrom <= :param。我不是在问如何修复查询,我可以自己做。但在我看来,Oracle和SQL Server在将日期值与空值进行比较时采用了不同的方法。我还没有能够谷歌这个主题的有用的东西,所以我想问,有没有人对这个有问题的请求?

1 个答案:

答案 0 :(得分:1)

我没有看到Oracle在param为null时返回任何问题,如此测试用例所示:

declare
  v_valid_from date;
  param date;

  procedure test1 (p_date_in in date)
  is
  begin
    for rec in (with record as (select to_date('01/01/2001', 'dd/mm/yyyy') validfrom, to_date('01/01/2015', 'dd/mm/yyyy') validto from dual union all
                                select to_date('01/01/2001', 'dd/mm/yyyy') validfrom, null validto from dual)
                select *
                from   Record rec 
                where  rec.validFrom <= p_date_in
                and    (rec.validTo is null or rec.validTo >= p_date_in))
    loop
      v_valid_from := rec.validfrom;
      dbms_output.put_line('p_date_in = "'||to_char(p_date_in, 'dd/mm/yyyy')||
                           ', v_valid_from = '||to_char(v_valid_from, 'dd/mm/yyyy'));
    end loop;

    dbms_output.put_line('p_date_in = "'||to_char(p_date_in, 'dd/mm/yyyy')||
                         ', final v_valid_from = "'||to_char(v_valid_from, 'dd/mm/yyyy')||'"');
  end test1;
begin
  test1(param);
  param := trunc(sysdate);
  test1(param);
end;
/

p_date_in = ", final v_valid_from = ""
p_date_in = "01/12/2015, v_valid_from = 01/01/2001
p_date_in = "01/12/2015, final v_valid_from = "01/01/2001"