arrays – 在postgresql中将列从字符串更改为字符串数组

前端之家收集整理的这篇文章主要介绍了arrays – 在postgresql中将列从字符串更改为字符串数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下是名为“容器”的表的片段.
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[]

Postgres中没有从varchar到varchar []的隐式转换.
您必须指明如何执行类型转换.
您应该在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 '{}';

猜你在找的Postgre SQL相关文章