gpt4 book ai didi

sql - 如何在 Postgresql 中使用 ALTER 将 VARCHAR 类型更改为 DATETIME?

转载 作者:行者123 更新时间:2023-11-29 14:21:16 24 4
gpt4 key购买 nike

如何在 Postgresql 中使用 ALTERVARCHAR() 类型更改为 DATETIME

列数据的结构如下:"2013-12-08 16:09:07"

最佳答案

你想要 USING clause to ALTER TABLE ... ALTER COLUMN ... TYPE , 和 the to_timestamp function .

ALTER TABLE mytable 
ALTER COLUMN thecolumn
TYPE TIMESTAMP WITH TIME ZONE
USING to_timestamp(thecolumn, 'YYYY-MM-DD HH24:MI:SS');

在这种情况下,由于数据看起来已经是一个有效的时间戳,您可以使用转换来简化它:

ALTER TABLE mytable 
ALTER COLUMN thecolumn
TYPE TIMESTAMP WITH TIME ZONE
USING to_timestamp(thecolumn::timestamp with time zone);

您会注意到我使用的类型名称是“timestamp with time zone”而不是“datetime”。那是因为在 PostgreSQL 中,datetime 只是 timestamp without time zone 的别名...但在大多数情况下,您实际上想使用 timestamp with time zone 代替。要了解有关时间戳的更多信息,see the manual .

关于sql - 如何在 Postgresql 中使用 ALTER 将 VARCHAR 类型更改为 DATETIME?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916350/

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