【问题标题】:convert int YYYYMMDD to date AS400将 int YYYYMMDD 转换为日期 AS400
【发布时间】:2019-04-27 03:10:12
【问题描述】:

我需要在 AS400 中将整数转换为日期格式。

我有一个名为ivdat8 的字段,它是格式为YYYYMMDD 的整数。

我需要使用 WHERE 子句来选择两个日期之间的数据,即今天和 3 天前。

我正在使用以下行来执行此操作:

Where
    ivdat8 Between (Select current date - 3 days from sysibm.sysdummy1) And (Select current date from sysibm.sysdummy1)

来自 sysibm 的当前日期是真正的日期格式,但 ivdat 是整数。

如何将 ivdat8 转换为可以在 WHERE 子句中使用的日期格式?

我已尝试以下方法将 int 转换为日期:

cast(cast(A.ivdat8 as varchar(50)) as date)

&

TIMESTAMP_FORMAT(ivdat8,'YYYYMMDD')

【问题讨论】:

  • 可以ivdat8 between cast(varchar_format(current date - 3 days, 'YYYYMMDD') as int) and cast(varchar_format(current date, 'YYYYMMDD') as int)吗?
  • 旁注:您通常应该使用包含下限 - >= - 上限不包含 - < 样式查询日期/时间/时间戳。一方面,考虑到今天永远不会结束(仅在昨天),我对包括“今天”在内的任何笼统的东西都有些怀疑。

标签: sql excel db2 ibm-midrange


【解决方案1】:

实际上最好不要转换ivdat8列数据,而是使用如下参数进行转换。

select ivdat8
from table (values 
  int(to_char(current date - 2 days, 'YYYYMMDD'))
, int(to_char(current date - 5 days, 'YYYYMMDD'))
) t (ivdat8)
where ivdat8 between 
    int(to_char(current date - 3 days, 'YYYYMMDD')) 
and int(to_char(current date, 'YYYYMMDD'));

【讨论】:

    【解决方案2】:

    在查询中不导致复杂转换的最简单方法是使用这个:

    cast(digits(cast(A.ivdat8 as dec(8))) || '000000' as date)
    

    完整的 where 子句也不需要从 sysibm.dummy1 中选择。

    where cast(digits(cast(A.ivdat8 as dec(8))) || '000000' as date) between current date - 3 days and current date
    

    如果您在 ivdat8 上构建了索引,那么最快的选择将是:

    where A.ivdat8 between cast(Current date - 3 days as dec(8)) and cast(Current Date as dec(8))
    

    【讨论】:

      【解决方案3】:

      设法将 int 转换为日期,首先我必须将其转换为字符串,然后使用 TO_DATE

      To_Date(cast(A.ivdat8 as varchar(50)),"YYYYMMDD")
      

      【讨论】:

        【解决方案4】:

        试试这个

        Where cast(TIMESTAMP_FORMAT(cast(ivdat8 as varchar(8)), 'YYYYMMDD') as date)                                                        
              Between (current date - 3 days) and current date
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多