微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 '{}';

原文地址:https://www.jb51.cc/postgresql/192789.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐