【问题标题】:ORACLE - Split string and create cursorORACLE - 拆分字符串并创建游标
【发布时间】:2021-04-13 20:39:06
【问题描述】:

我遇到了 oracle 主题的问题

我们有一个表,其中一个列存储用逗号 (,) ex 分隔的数据

id type item
1 1 1234567890,A,asd,12345
2 1 8456321790,B,dde,12345

我们需要能够分离该值并得到类似的结果

col1 col2 col3 col4
1234567890 A asd 12345
8456321790 B dde 12345

但是这个列的数量不是固定的,某些类型可能是不同的数据湖,我们需要动态响应,例如

id type item
1 1 1234567890,A,asd,12345
2 1 8456321790,B,dde,12345
3 2 1111155555
4 2 7777788888

如果我运行 1 个进程,结果和以前一样

col1 col2 col3 col4
1234567890 A asd 12345
8456321790 B dde 12345

但如果我为类型 2 运行它,结果应该如下

col1
1111155555
7777788888

我们可以将 item 字段转换为 varchar2 的表,但我们找不到如何将其转换为与光标一起使用。 任何的想法? 非常感谢你! 对不起,如果我的英语听不懂,那不是我的母语。

【问题讨论】:

  • 嗯,这无疑是您必须处理的错误数据模型。您不能只提供查询中的最大列数并将未使用的列留空吗?六列示例:type 1: col1=1234567890, col2=A, col3=asd, col4=12345, col5=null, col6=null。 类型 2: col1=1111155555,col2=null,col3=null,col4=null,col5=null,col6=null。那会让事情变得更容易。或者更好的是:你能改变数据模型吗? :-)

标签: oracle


【解决方案1】:

你真的在乎是哪个type吗?这行吗? (第 1 - 6 行中的示例数据;实际查询从第 7 行开始):

SQL> with test (type, item) as
  2    (select 1, '1234567890,A,asd,12345' from dual union all
  3     select 1, '8456321790,B,dde,12345' from dual union all
  4     select 2, '1111155555' from dual union all
  5     select 2, '7777788888' from dual
  6    )
  7  select
  8    regexp_substr(item, '\w+', 1, 1) col1,
  9    regexp_substr(item, '\w+', 1, 2) col2,
 10    regexp_substr(item, '\w+', 1, 3) col3,
 11    regexp_substr(item, '\w+', 1, 4) col4
 12  from test;

COL1       COL2       COL3       COL4
---------- ---------- ---------- ----------
1234567890 A          asd        12345
8456321790 B          dde        12345
1111155555
7777788888

SQL>

【讨论】:

    【解决方案2】:

    CASE 接线员来救你了

    select id, 
           case when type = 1 then substr(item, 1, instr(item, ',')-1) else item end col1,
           case when type = 1 then substr(item, instr(item, ',')+1, instr(item, ',', 1, 2)-instr(item, ',') - 1) end col2,
           case when type = 1 then substr(item, instr(item, ',', 1, 2) + 1, instr(item, ',', 1, 3) - instr(item, ',', 1, 2) - 1) end col3,
           case when type = 1 then substr(item, instr(item, ',', 1, 3) + 1, length(item) - instr(item, ',', 1, 3)) end col4
      from some_table
    

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多