如何在PostgreSQL11.0中根据正则表达式更改列的日期格式

我在 PostgreSQL 11.0 中有一个表,其中包含带有日期的以下列(列类型:不同的字符)。

id   date_col
1    April2006
2    May2005
3    null
4
5    May16,2019

我想将列转换为“日期”

由于有两种不同的日期格式,我使用 CASE 语句根据日期模式更改列类型。

select *,case
                when date_col ~ '^[A-Za-z]+\d+,\d+' then alter table tbl alter date_col type date using to_date((NULLIF(date_col,'null')),'MonthDD,YYYY')
                when date_col ~ '^[A-Za-z]+,'MonthYYYY')
                else null
                end

from tbl

我收到以下错误:

[Code: 0,SQL State: 42601]  ERROR: syntax error at or near "table"
  Position: 93  [Script position: 93 - 98]

预期输出为:

id   date_col
1    2006-04-01
2    2005-05-01
3    null
4
5    2019-05-16

非常感谢任何帮助!!

smazhe 回答:如何在PostgreSQL11.0中根据正则表达式更改列的日期格式

您绝对不能一次更改一行一行。最好的办法是更新现有值,使它们都具有相同的格式,然后发出单个 ALTER 语句。

本文链接:https://www.f2er.com/541543.html

大家都在问