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

时间:2018-04-26 22:14:45

标签: sql stored-procedures firebird date-arithmetic firebird2.1

我需要显示自特定日期以来经过的时间,包括年,月和日,考虑闰年/月数。这必须在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;

关于如何修复它的任何想法?

1 个答案:

答案 0 :(得分:0)

这是在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;