簡體   English   中英

如何在PostgreSQL11.0中根據正則表達式更改列的日期格式

[英]How to change date format of a column based on regex in 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]+,\d+' then alter table tbl alter date_col type date using to_date((NULLIF(date_col, 'null')), 'MonthYYYY')
                else null
                end

from tbl

我收到以下錯誤:

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

預期的 output 為:

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

任何幫助都非常感謝!

您絕對不能一次更改一列。 最好的辦法是更新現有值,使它們都具有相同的格式,然后發出一個 ALTER 語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM