将列类型从 char 更改为 array
Changing a column type from char to array
我在 PostgreSQL 中有一个 table,它有一个 character(1)
列,我想将其更改为 text[]
列,但我似乎无法让它工作:
ALTER TABLE public.mytable
ALTER COLUMN abc TYPE TEXT[] COLLATE pg_catalog."default"
USING ARRAY[abc];
给我这个错误:
ERROR: default for column "abc" cannot be cast automatically to type text[]
这是可以理解的,因为 Postgres 无法将 NULL:bpchar
转换为数组。但是,我该如何完成呢?显然,可以输入 NULL
s ...
您需要删除默认值,更改数据类型并重新添加默认值。
来自 documentation:
(…) the USING expression is not applied to the column's default value (if any); (…).
This means that when there is no implicit or assignment cast from old to new type, SET DATA TYPE might fail to convert the default even though a USING clause is supplied. In such cases, drop the default with DROP DEFAULT, perform the ALTER TYPE, and then use SET DEFAULT to add a suitable new default.
和给定的例子:
> When the column has a default expression that won't automatically cast to the
new data type:
ALTER TABLE foo
ALTER COLUMN foo_timestamp DROP DEFAULT,
ALTER COLUMN foo_timestamp TYPE timestamp with time zone
USING timestamp with time zone 'epoch' + foo_timestamp * interval '1 second',
ALTER COLUMN foo_timestamp SET DEFAULT now();
我在 PostgreSQL 中有一个 table,它有一个 character(1)
列,我想将其更改为 text[]
列,但我似乎无法让它工作:
ALTER TABLE public.mytable
ALTER COLUMN abc TYPE TEXT[] COLLATE pg_catalog."default"
USING ARRAY[abc];
给我这个错误:
ERROR: default for column "abc" cannot be cast automatically to type text[]
这是可以理解的,因为 Postgres 无法将 NULL:bpchar
转换为数组。但是,我该如何完成呢?显然,可以输入 NULL
s ...
您需要删除默认值,更改数据类型并重新添加默认值。
来自 documentation:
(…) the USING expression is not applied to the column's default value (if any); (…).
This means that when there is no implicit or assignment cast from old to new type, SET DATA TYPE might fail to convert the default even though a USING clause is supplied. In such cases, drop the default with DROP DEFAULT, perform the ALTER TYPE, and then use SET DEFAULT to add a suitable new default.
和给定的例子:
> When the column has a default expression that won't automatically cast to the
new data type:
ALTER TABLE foo
ALTER COLUMN foo_timestamp DROP DEFAULT,
ALTER COLUMN foo_timestamp TYPE timestamp with time zone
USING timestamp with time zone 'epoch' + foo_timestamp * interval '1 second',
ALTER COLUMN foo_timestamp SET DEFAULT now();