加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:30:13 所属栏目:百科 来源:网络整理
导读:以下是名为“容器”的表的片段. Column | Type | Modifiers --------------------+-----------------------------+--------------------------------- id | uuid | not null name | character varying(255) | products | character varying | default '{}'::
以下是名为“容器”的表的片段.
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 '{}';

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读