Column | Type | Modifiers --------------------+-----------------------------+--------------------------------- id | uuid | not null name | character varying(255) | products | character varying | default '{}'::character varying
如何将products列更改为“character varying []”,并将相应的修饰符更改为默认的“{}”:: character varying []?本质上,我想将字符串转换为字符串数组.请注意,products列对字符数没有限制.
alter table "containers" alter "products" type character varying[];
抛出以下错误
ERROR: column “products” cannot be cast to type character varying[]
您必须指明如何执行类型转换.
您应该在USING表达式子句中执行此操作(请参阅文档中的 ALTER TABLE).
在这种情况下,您必须删除并重新创建列的默认值,如文档中所述:
The USING option of SET DATA TYPE can actually specify any expression involving the old values of the row; that is,it can refer to other columns as well as the one being converted. This allows very general conversions to be done with the SET DATA TYPE Syntax. Because of this flexibility,the USING expression is not applied to the column’s default value (if any); the result might not be a constant expression as required for a default. 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.
alter table containers alter products drop default; alter table containers alter products type text[] using array[products]; alter table containers alter products set default '{}';
这三个操作可以在一个语句中完成:
alter table containers alter products drop default,alter products type text[] using array[products],alter products set default '{}';