如何将没有时区的时间转换为没有时区的时间戳?

8

我需要将PSQL中一张表中的几列进行转换,但我真的不想删除表来解决这个问题(那是我的最后手段)。有没有办法可以做到这一点,因为当我输入以下内容时:

    ALTER TABLE table ALTER TABLE column type TIMESTAMP without time zone using column::TIMESTAMP without time zone; 

它不能工作,说:

    ERROR:cannot cast type time without time zone to timestamp without time zone.

补充一点,如果可能的话,我希望避免删除列,因为我已经使用了这些列的索引。


1
能否添加新列,更新表格并删除旧列? - Derrick Moeller
刚刚编辑了一下,我想避免那个哈哈 - Marko Petričević
你需要改变100%的索引,因此放弃更改索引类型并创建另一个索引可能会更快。 - Vao Tsun
2个回答

13
如果您想要日期部分为今天:
alter table the_table
alter column the_column type timestamp without time zone 
using current_date + the_column

你能详细说明吗?我感到困惑。 - alramdein
你能详细说明一下吗?我有点困惑。 - undefined

1

Postgresql不允许直接将没有时区的时间转换为没有时区的时间戳。

您只需要先将其转换为没有时区的时间,然后再将字符变量更改为没有时区的时间戳即可。

您可以参考以下查询:

  1. 更改为字符变量:
ALTER TABLE table_name
ALTER COLUMN colum_name TYPE character varying
USING column_name::character varying

现在我们来将时间戳转换为没有时区的格式:
ALTER TABLE table_name
ALTER COLUMN colum_name TYPE Timestamp without time zone
USING column_name::Timestamp without time zone

现在您将能够成功更新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接