首页 > 解决方案 > 我们如何在 SQLITE 中将 clob 字段的子字符串转换为日期时间?

问题描述

示例数据字段如下:

DATE+05/06/2022 23:59:59;
DATE+06/05/2022 23:59:59;
DATE+14/05/2022 23:59:59;
DATE+26/05/2022 23:59:59;

我们在日期中的 SUBSTR 数据为:

05/06/2022 23:59:59
06/05/2022 23:59:59
14/05/2022 23:59:59
26/05/2022 23:59:59

必填日期字段如下:

2022-06-05 23:59:59
2022-05-06 23:59:59
2022-05-14 23:59:59
2022-05-26 23:59:59

我尝试过的将 NULL 填充为最终结果的事情:

我发现不相关的链接:

我正在寻找除拆分和连接日期字段之外的任何其他方式。

标签: sqlsqlitedatedatetimeselect

解决方案


SQLite 没有将字符串转换为日期的内置函数。您需要使用字符串函数来重新组合日期。

对于格式 lke: 'DATE+05/06/2022 23:59:59;',您可以执行以下操作:

substr(mycol, 12, 4) 
|| '-' || substr(mycol, 9,  2)
|| '-' || substr(mycol, 6,  2)
|| ' ' || substr(mycol, 17, 8)

DB Fiddle 上的演示

with mytable as (
    select 'DATE+05/06/2022 23:59:59;' mycol
    union all select 'DATE+06/05/2022 23:59:59;'
    union all select 'DATE+14/05/2022 23:59:59;'
    union all select 'DATE+26/05/2022 23:59:59;'
)
select substr(mycol, 12, 4) 
        || '-' || substr(mycol, 9,  2)
        || '-' || substr(mycol, 6,  2)
        || ' ' || substr(mycol, 17, 8) mydate
from mytable
| 我的日期 |
| :----------------- |
| 2022-06-05 23:59:59 |
| 2022-05-06 23:59:59 |
| 2022-05-14 23:59:59 |
| 2022-05-26 23:59:59 |

推荐阅读