如何在 Postgresql 中使用 ALTER
将 VARCHAR()
类型更改为 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/