问题
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