在存储过程中使用 DateDiff 计算年龄(年、月、日)

Calculate age (year, month, day) using DateDiff in stored procedure

我需要以年、月和日为单位显示自特定日期以来经过的时间,考虑飞跃 years/months。这必须在 Firebird 2.1 的存储产品中。

我正在努力处理以下代码:

  SELECT CASE
    WHEN :CustomDateTime > CURRENT_DATE THEN 0
    WHEN EXTRACT(YEARDAY FROM :CustomDateTime) > EXTRACT(YEARDAY FROM CURRENT_DATE) THEN DATEDIFF(YEAR, :CustomDateTime, CURRENT_DATE) - 1
    ELSE DATEDIFF(YEAR, :CustomDateTime, CURRENT_DATE)
  END
  FROM RDB$DATABASE
  INTO :YearDiff;

  SELECT CASE
    WHEN :CustomDateTime > CURRENT_DATE THEN 0
    WHEN (EXTRACT(MONTH FROM :CustomDateTime) = EXTRACT(MONTH FROM CURRENT_DATE))
       AND (EXTRACT(YEARDAY FROM :CustomDateTime) > EXTRACT(YEARDAY FROM CURRENT_DATE))
      THEN DATEDIFF(MONTH, DATEADD(:YearDiff YEAR TO :CustomDateTime), CURRENT_DATE) - 1
    ELSE DATEDIFF(MONTH, DATEADD(:YearDiff YEAR TO :CustomDateTime), CURRENT_DATE)
  END
  FROM RDB$DATABASE
  INTO :MonthDiff;

  SELECT CASE
    WHEN :CustomDateTime > CURRENT_DATE THEN 0
    WHEN (:YearDiff > 0) AND (:MonthDiff > 0) THEN DATEDIFF(DAY, DATEADD(:MonthDiff MONTH TO DATEADD(:YearDiff YEAR TO :CustomDateTime)), CURRENT_DATE)
    WHEN (:YearDiff > 0) AND (:MonthDiff = 0) THEN DATEDIFF(DAY, DATEADD(:YearDiff YEAR TO :CustomDateTime), CURRENT_DATE)
    WHEN (:YearDiff = 0) AND (:MonthDiff > 0) THEN DATEDIFF(DAY, DATEADD(:MonthDiff MONTH TO :CustomDateTime), CURRENT_DATE)                
    ELSE DATEDIFF(DAY, :CustomDateTime, CURRENT_DATE)
  END
  FROM RDB$DATABASE
  INTO :DayDiff;

有什么解决办法吗?

这是在 pl/sql 中,但您可以使用这个想法来查找自 v_date 以来经过的时间;

 set serveroutput on;
    declare
    v_date date := '27-APR-16';
    PROCEDURE passed(toCheck date) IS 
             years INTEGER := 0;
             months INTEGER := 0;
             days INTEGER := 0;
    BEGIN
            SELECT floor(MONTHS_BETWEEN(sysdate, toCheck)) into months FROM dual;
            SELECT SYSDATE - ADD_MONTHS(toCheck, months) INTO days FROM dual;
            years := floor(months / 12);
            months := months - (years * 12);
            dbms_output.put_line('Yers : ' || years || ', ' || ' Months : ' || months || ', Days: ' || days);
    END passed;
    begin
        passed(v_date);
    end;