使用oracle通过分隔符位置拆分String

时间:2017-01-30 16:20:04

标签: oracle

我有一个类似' ,, defoifcd,87765'在oracle table.Means中,前两个字符串是空的。所以我需要在Oracle.i中用逗号分隔字符串作为分隔符我正在编写此查询

SELECT  
REGEXP_SUBSTR (TEST_STRING, '[^,]+', 1, 1)    AS part_1,
REGEXP_SUBSTR (TEST_STRING, '[^,]+', 1, 2)    AS part_2,
REGEXP_SUBSTR (TEST_STRING, '[^,]+', 1, 3)    AS part_3,
REGEXP_SUBSTR (TEST_STRING, '[^,]+', 1, 4)    AS part_4
FROM ABCD
;

这里ABCD是我的桌子,TEST_STRING是我的库存。

但结果返回

PART_1,  part_2,  part_3,  part_4
defoifcd,87765

但我希望结果如,

PART_1,  part_2,  part_3,  part_4
                  defoifcd, 87765

意味着我需要' defoifcd'和' 87765' part_3和part_4列中的值,因为前两个字符串为空,但是从我的查询中,它是part_1和part_2列中的comimg。

1 个答案:

答案 0 :(得分:1)

如果你只有一个字符串而且你知道它总是有四个部分,你可以像这样分割它,只使用标准字符串函数(并避免使用更灵活但通常更慢的正则表达式)。

注意:此答案的后半部分解决了具有可变数量“部分”的字符串。

with inputs ( str ) as (
       select ',,defoifcd,87765' from dual
     )
-- end of TEST data; SQL query begins below (use your actual table and column names)
select substr(str, 1, instr(str, ',') - 1) as part_1,
       substr(str, instr(str, ',') + 1, 
              instr(str, ',', 1, 2) - instr(str, ',') - 1) as part_2,
       substr(str, instr(str, ',', 1, 2) + 1, 
              instr(str, ',', 1, 3) - instr(str, ',', 1, 2) - 1) as part_3,
       substr(str, instr(str, ',', -1) + 1) as part_4
from   inputs;

PART_1   PART_2   PART_3   PART_4
-------- -------- -------- --------
                  defoifcd 87765

1 row selected.

如果事先不知道部件数量,最好以不同的格式获得输出(参见下面的输出)。如果需要在完成所有其他处理后可以完成的列中排列部件 - 并且最好留给报告应用程序而不是在SQL中完成。

with inputs ( id, str ) as (
       select 1, ',,defoifcd,87765' from dual union all
       select 2, ''                 from dual union all
       select 3, 'a, b, c'          from dual
     )
-- end of TEST data; SQL query begins below (use your actual table and column names)
select id, str, level as part_number,
       substr(aug_str, instr(aug_str, ',', 1, level) + 1,
              instr(aug_str, ',', 1, level + 1) - instr(aug_str, ',', 1, level) - 1) as val
from   ( select id, str, ',' || str || ',' as aug_str from inputs)
connect by level <= length(str) - length(translate(str, 'z,', 'z')) + 1
       and prior id = id
       and prior sys_guid() is not null
;

ID STR              PART_NUMBER VAL
-- ---------------- ----------- ----------
 1 ,,defoifcd,87765           1
 1 ,,defoifcd,87765           2
 1 ,,defoifcd,87765           3 defoifcd
 1 ,,defoifcd,87765           4 87765
 2                            1
 3 a, b, c                    1 a
 3 a, b, c                    2  b
 3 a, b, c                    3  c

8 rows selected.
相关问题