arrays - 如何将一列以逗号分隔的字符串转换为字符串数组

标签 arrays postgresql ddl

我在 PostgreSQL 中有这个表,其中一列是一个包含 nconst 的字符串,称为 directors。字符串的格式为 nm00386378,nm97284993,我需要将每个字符串转换为数组,例如:{"nm00386378","nm97284993"}

我尝试了以下代码,但我认为它只是将字符串转换为单值数组:

alter table crew_text
    alter directors drop default,
    alter directors type text[] using array[directors],
    alter directors set default '{}';

我得到了 {"nm00386378,nm97284993"} 数组值,但我期待 {"nm00386378","nm97284993"}

最佳答案

使用string_to_array()像这样:

alter table crew_text
   alter directors drop default
,  alter directors type text[] using string_to_array(directors, ',')
,  alter directors set default '{}';

db<> fiddle here

仅在需要时才使用正则表达式函数。这些功能更强大,但也更棘手,而且成本更高。

关于arrays - 如何将一列以逗号分隔的字符串转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58122598/

相关文章:

arrays - SystemVerilog foreach 语法,用于循环遍历多维数组的低维

c - 了解如何将 main(){} 中出现的一段代码转换为 C 中的一个或多个函数

javascript - 如何查找存储在数组中的字符串中的数字总和

MySQL - 防止一行引用自身

java - 将 Oracle 或 Sql Server DDL 转换为 Derby

arrays - ruby 返回存在于每个嵌套数组中的值数组

java - 组织.postgresql.util.PSQLException : No value specified for parameter 1

postgresql - 按日期范围分区 PostgreSQL 扫描所有分区

PostgreSQL:如何获取以前的插入时间戳

mysql - 添加外键约束时出现语法错误