【问题标题】:How to change Data Type with using Case Statement如何使用 Case 语句更改数据类型
【发布时间】:2017-02-28 08:07:12
【问题描述】:

我有这样的代码

SELECT CASE 
              WHEN gift_club_end_date = ' ' THEN ' '
              WHEN gift_club_end_date = '00000000' THEN ' '
              ELSE TO_DATE(gc.gift_club_end_date, 'yyyymmdd')

              END

       FROM gift_clubs gc

错误是

ORA-00932;不一致的数据类型:预期的 CHAR 得到了 DATE

gift_club_end_date 的数据类型是 VARCHAR2。

我想改成日期

例如如果有行

20160802

然后它显示

2016 年 8 月 2 日

但是有些行是空白的,00000000

所以我想在这些行上显示/更改为空白,如果为空白或 00000000

我怎样才能这样编码而不引起错误

非常感谢

【问题讨论】:

  • 您是否使用单个空格 (' ') 来表示空值? AND:您希望查询返回什么 - 字符串或日期?

标签: oracle date select type-conversion


【解决方案1】:

您可能需要以下内容:

with gift_clubs(gift_club_end_date) as
(
    select '20160802' from dual union all
    select '00000000' from dual union all
    select null       from dual
)
select case
        when gift_club_end_date = '00000000'
            then to_date(null)
        when gift_club_end_date is null
            then to_date(null)
        when gift_club_end_date = ' '
            then to_date(null)
        else
            to_date(gift_club_end_date, 'yyyymmdd')
       end
from gift_clubs

这考虑了 null 和包含单个空格的字符串的情况;您可能只需要其中一个,因此请相应地编辑该语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2021-10-22
    • 1970-01-01
    • 2013-09-23
    • 2021-12-27
    • 2017-02-07
    相关资源
    最近更新 更多