I needed to change all tables columns in the whole DB from data type timestamp
without
time zone
to timestamp(0)
with
time zone
.
So I created this function:
CREATE OR REPLACE FUNCTION grd_replace_datetime_with_timezone()
RETURNS character varying AS
$BODY$
DECLARE
old_column RECORD;
s text;
BEGIN
FOR old_column IN (
SELECT
isc.table_schema as table_schema,
isc.table_name as table_name,
isc.column_name as column_name
FROM
information_schema.columns isc
INNER JOIN
pg_tables pt
ON (isc.table_schema = pt.schemaname and isc.table_name = pt.tablename)
WHERE
isc.column_name like '%date%' and
isc.table_schema in ('public') and
isc.data_type = 'timestamp without time zone'
ORDER BY
isc.table_name ASC
)
LOOP
RAISE NOTICE 'Schema: %',old_column.table_schema;
RAISE NOTICE 'Table: %',old_column.table_name;
RAISE NOTICE 'Column %',old_column.column_name;
EXECUTE 'ALTER TABLE '||old_column.table_schema||'.'||old_column.table_name||'
ALTER COLUMN '||old_column.column_name||' TYPE timestamp(0) with time zone';
RAISE NOTICE '-------------------------------------------------------------------------------';
RAISE NOTICE '';
END LOOP;
RETURN 'S';
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
But some views depend on affected columns and I got error:
ERROR: cannot alter type of a column used by a view or rule
Also I got error about indexes.
How to change the data type for all timestamp without time zone
columns?