在oraclesql中拆分字符串数组

goqiplq2  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(485)

我想在oracle sql中使用regex.substr将一个列值拆分为多个列。此列包含两种格式的字符串
a) 字符串数组,例如:[“”,“def”]
b) 单字符串,如“”
我正在使用

regexp_substr(col1, '[^",]+', 1, 1) as val1,
regexp_substr(col1, '[^",]+', 1, 2) as val2,
regexp_substr(col1, '[^",]+', 1, 3) as val3,
regexp_substr(col1, '[^",]+', 1, 4) as val4,

使用上述方法,我只能拆分格式“b”
对于格式b),我得到以下结果

val1   val2   val3   val4
  [     abc   def     ]

我不希望结果中包含方括号。请就如何进行这项工作提出建议。提前谢谢!

agyaoht7

agyaoht71#

regexp\u substr(列1,“[^”,]+”,1,1)
它只会返回 NON-NULL 数组中的值。可能有 NULL 数组中的值,因此下面的查询将返回数组中元素的确切位置,并考虑空值:

with data as 
(
  select '["abc","def","xyz","klm","nop","qrs"]' arr from dual union all
  select '["abc",,"xyz","klm","nop","qrs"]' arr from dual union all
  select '["abc","def",,"lkj",]' arr from dual
)
select 
    regexp_substr(arr, '(.*?)(,|$)', 1, 1, NULL, 1) col1,
    regexp_substr(arr, '(.*?)(,|$)', 1, 2, NULL, 1) col2,
    regexp_substr(arr, '(.*?)(,|$)', 1, 3, NULL, 1) col3,
    regexp_substr(arr, '(.*?)(,|$)', 1, 4, NULL, 1) col4,
    regexp_substr(arr, '(.*?)(,|$)', 1, 5, NULL, 1) col5,
    regexp_substr(arr, '(.*?)(,|$)', 1, 6, NULL, 1) col6
from 
(
 select replace(replace(replace(arr, '['), '"'), ']') arr from data
);

COL1 COL2 COL3 COL4 COL5 COL6
---- ---- ---- ---- ---- ----
abc  def  xyz  klm  nop  qrs 
abc       xyz  klm  nop  qrs 
abc  def       lkj

相关问题