PostgreSQL => ALTER TABLE without timezone -> with timezone, using select for TZ

冷暖自知 提交于 2021-02-08 10:26:05

问题


I'm trying to convert the column, and preserve the data in the specified timezone. I have a script, but it errors out on the SELECT at the end.

ALTER TABLE schema.table 
ALTER COLUMN column_date TYPE TIMESTAMP WITH TIME ZONE
USING column_date AT TIME ZONE (SELECT value FROM schema.table WHERE id = 'timezone');

ERROR:  cannot use subquery in transform expression

I have time zones stored, but trying to pull that back to apply to the script is posing a challenge. I know I can simply hardcode the timezone as 'EST|CST|PST', etc. but I have multiple databases this needs to be applied to (with multiple alters per DB), hence the required SELECT at the end. Is there a way to accomplish this?

I've poured over a few questions on this subject; while some came close, they don't quite meet the needs (My apologies if this is a duplicate, I've spent a while searching for an answer).

[RESOLVED]: Using 2 separate queries

ALTER TABLE schema.table 
ALTER COLUMN column_date TYPE TIMESTAMP WITH TIME ZONE;

UPDATE schema.table 
SET column_date = column_date AT TIME ZONE 
    (SELECT value FROM schema.table WHERE id = 'timezone');

回答1:


You can use dynamic SQL:

DO
$$BEGIN
   EXECUTE format('ALTER TABLE ... AT TIME ZONE %L',
                  (SELECT value FROM atable ...));
END;$$;


来源:https://stackoverflow.com/questions/55006575/postgresql-alter-table-without-timezone-with-timezone-using-select-for-tz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!