在 Oracle 中减去返回 0 的日期

Subtraction of dates returning 0 in Oracle

我创建了以下函数:

create or replace function tempo_medio_atendimento_dia return number is
  counter number; 
  last_date date;
  date_diff number;
  type_info varchar(100);
  cursor c1 is select e.data_pedido from encomenda e, funcionario f where e.funcionario.codigo = f.codigo and to_char(e.data_pedido, 'YYYY-MM-DD') = '2015-04-23' order by e.data_pedido;
  begin
    counter := 0.0;    
    for c1_x in c1 loop
      last_date := to_date(c1_x.data_pedido);
      select dump(last_date) into type_info from dual;
      DBMS_OUTPUT.PUT_LINE('TYPE INFO: ' || type_info);
      if c1%rowcount > 1 then 
        DBMS_OUTPUT.PUT_LINE('DATE:' || c1_x.data_pedido || ' - ' || last_date || ' = ' || (to_date(c1_x.data_pedido) - to_date(last_date)) * 24 * 60 * 60);
        select (to_date(c1_x.data_pedido) - to_date(last_date)) * 24 * 60 * 60 into date_diff from dual;
        counter := counter + date_diff;
      end if;
    end loop;
    return counter;
end tempo_medio_atendimento_dia;

日期打印正确,我检查了 c1_x.data_pedido 类型,它是 12(DATE),但出于某种原因,当我尝试减去日期时,它 returns 0.

select (to_date(c1_x.data_pedido) - to_date(last_date)) * 24 * 60 * 60 into date_diff from dual;

但是,如果我直接运行下面的代码,它returns360,正如它所设想的那样。

select (to_date('23/04/2015 10:49:12') - to_date('23/04/2015 10:43:12')) * 24 * 60 * 60 from dual;

由于函数中的数据类型似乎是正确的,我不明白为什么减法不起作用。有什么建议吗?

你在循环中做的第一件事是

last_date := to_date(c1_x.data_pedido);

这意味着稍后当您执行以下操作时

to_date(c1_x.data_pedido) - to_date(last_date)

您正在减去 c1_x.data_pedido - c1_x.data_pedido

除此之外,我建议不要尝试将日期作为日期。我不知道 data_pedido 的数据类型,但 last_date 肯定已经是一个日期,所以调用 TO_DATE 是不必要的。