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');
You can use dynamic SQL:
DO
$$BEGIN
EXECUTE format('ALTER TABLE ... AT TIME ZONE %L',
(SELECT value FROM atable ...));
END;$$;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.