【问题标题】:alter column from time with time zone to timestamp将列从带有时区的时间更改为时间戳
【发布时间】:2013-08-17 18:34:45
【问题描述】:

我无法在我的 Postgres 数据库中将名为 key_request 的表中名为 end_date 的列从 time with time zone 更改为 timestamp。我尝试使用以下代码:

alter table key_request alter column end_date type timestamp with time zone using end_date::timestamp with time zone

我不断收到以下错误:

ERROR:  cannot cast type time with time zone to timestamp with time zone

知道如何调整此查询以使其正常工作吗?

【问题讨论】:

  • 我觉得你写错了,你想把timestamp without timezone转换成timestamp with timezone,对吧?
  • 不,该列是带时区的时间,我希望更改为带时区的时间戳
  • 哦!抱歉...现在我明白了,我一直在阅读 timestamp 而不是 time... 哈哈...

标签: sql postgresql timestamp postgresql-9.2 alter


【解决方案1】:

你可以这样做:

alter table key_request
alter column end_date type timestamp with time zone using date('20130101') + end_date;

sql fiddle demo

【讨论】:

【解决方案2】:

我会通过一系列步骤来做到这一点

  1. 更改表格,将新列 end_date1 添加为 time with time zone
  2. 将日期从end_date(旧)复制到end_date1
  3. 更改表格,删除旧的 end_date
  4. 改变表,将end_date1扩孔到end_date

【讨论】:

  • 工作正常,但有没有办法可以将新列放回旧列的位置而不删除其间的列?
  • postgresql 不支持更改现有表中的列顺序。如果您“真的”需要它位于特定位置(这不是您需要它的正当理由),那么您需要重新创建整个表。
  • 使用@Roman Pekar 的解决方案,您不必删除该列。
【解决方案3】:

java.sql.Date 更改为java.util.Date

ALTER TABLE key_request ALTER COLUMN end_date TYPE timestamp without time zone;

如果您有与该表相关的依赖视图

  1. 丢弃视图
  2. 更改列类型
  3. 重新创建视图

在类型迁移时来自 java/hibernate 方法的解决方案。

  • java.sql.Date 被翻译成date
  • java.util.Date 被翻译成timestamp without time zone

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2020-11-27
    • 2021-06-25
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多