How to calculate the difference between two dates with a return value type of integer in Informix?

£可爱£侵袭症+ 提交于 2020-01-15 07:03:10

问题


I am using an Informix database. I want to get the difference between two dates, and the data type of return value must be an integer. The SQL looks like:

select (today - to_date('20121201','%Y%m%d'))  from your_table_name

However, when I execute the SQL it returns 45 and certainly the computed value is not the integer type. What's the date type of the value? How can I cast the value to integer?


回答1:


The TO_DATE function is an Oracle import, and returns an Oracle DATE type in Oracle (hence the name), but the Oracle DATE type corresponds to an Informix DATETIME type. So, the Informix implementation of the TO_DATE() function returns a DATETIME type.

Problem

SELECT TODAY AS TODAY,
       TO_DATE('20121201', '%Y%m%d') AS raw_to_date,
       (TODAY - TO_DATE('20121201','%Y%m%d')) AS raw_difference
  FROM sysmaster:informix.sysdual;

today       raw_to_date                   raw_difference
DATE        DATETIME YEAR TO FRACTION(5)  INTERVAL DAY(8) TO DAY
2013-01-16  2012-12-01 00:00:00.00000     46

Solution

The solution for your expression is to apply the DATE function to the output of TO_DATE, or cast it to type DATE.

SELECT DATE(TO_DATE('20121201', '%Y%m%d'))          AS date_to_date,
       CAST(TO_DATE('20121201', '%Y%m%d') AS DATE)  AS cast_to_date,
            TO_DATE('20121201', '%Y%m%d')::DATE     AS colon_to_date,
       (TODAY - DATE(TO_DATE('20121201','%Y%m%d'))) AS date_difference
  FROM sysmaster:informix.sysdual;

date_to_date  cast_to_date  colon_to_date  date_difference
DATE          DATE          DATE           INTEGER
2012-12-01    2012-12-01    2012-12-01     46



回答2:


The difference between two dates should be an integer. You should only get an INTERVAL when computing the difference between DATETIME values.

I don't have an Informix instance handy right now, but I suspect the use of the to_date() function is resulting in DATETIME math.

I can see you've come up with a solution, but try the following, which would be a lot simpler:

SELECT today - TO_DATE('20121201', '%Y%m%d')::DATE AS td FROM tb_dis_controll


来源:https://stackoverflow.com/questions/14331328/how-to-calculate-the-difference-between-two-dates-with-a-return-value-type-of-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!