gpt4 book ai didi

sql - 将字符字段更改为日期

转载 作者:行者123 更新时间:2023-11-29 12:01:02 25 4
gpt4 key购买 nike

我有一个遗留的 postgres 数据库,它的日期列被转换为 character(50) 字段(不要问)。我想更改表格和列以包含实际日期。因为这有效:

select distinct to_date(date_begin, 'YYYY DD MM') from dates;

我天真地认为这可能有效:

alter table dates alter column date_begin type character
using to_date(date_begin, 'YYYY DD MM');

但事实并非如此。有什么线索吗?

最佳答案

只是按照 OP 的意图工作。我们这里有一个简单的 thinko/typo。
manual about ALTER TABLE 中阅读更多内容.
演示:

-- DROP SCHEMA x CASCADE;
CREATE SCHEMA x;
CREATE TABLE x.tbl(date_begin character(50));
INSERT INTO x.tbl VALUES ('2011-11-11 11:11'), (NULL), (''), ('1977');
-- NULL and empty string work too
-- even just YYYY works: '1977' .. is converted to '1977-01-01' automatically
-- empty string produce a possibly surprising result: '0001-01-01 BC'

ALTER TABLE x.tbl ALTER COLUMN date_begin TYPE date USING to_date(date_begin, 'YYYY DD MM');

SELECT * FROM x.tbl;

提示:您写的是 type character 而不是 type date

关于sql - 将字符字段更改为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8099352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com