【问题标题】:oracle sql split string to rowsoracle sql将字符串拆分为行
【发布时间】:2016-04-18 02:52:31
【问题描述】:

我有字符串 'ABC' 我需要分成如下几行

A
B
C

.我知道分隔符存在时该怎么做。不存在分隔符时怎么样

with test as
(select 'A,B,C' col1 from dual)
  select regexp_substr(col1, '[^,]+', 1, rownum) result1
  from test
  connect by level <= length(regexp_replace(col1, '[^,]+')) + 1;

【问题讨论】:

  • 是否总是 3 个字符后用逗号分隔?

标签: sql oracle select oracle11g


【解决方案1】:

你可以使用这样的函数

-- define type
CREATE OR REPLACE TYPE TABLE_OF_STRING AS TABLE OF VARCHAR2(32767);

-- function
function SPLIT_STRING_TO_STRINGS
  (
    p_list varchar2,
    p_delimiter varchar2 := ','
  ) return TABLE_OF_STRING pipelined
  is
    l_idx    pls_integer;
    l_list    varchar2(32767) := p_list;
  begin
    loop
        l_idx := instr(l_list, p_delimiter);
        if l_idx > 0 then
            pipe row(substr(l_list, 1, l_idx-1));
            l_list := substr(l_list, l_idx + length(p_delimiter));
        else
            pipe row(l_list);
            exit;
        end if;
    end loop;
    return;
  end SPLIT_STRING_TO_STRINGS;

-- usage example
select * from table(SPLIT_STRING_TO_STRINGS('A,B,C',','))

【讨论】:

    【解决方案2】:

    没有分隔符应该更容易 - 使用相同的方法,但只需使用 substrlevel 作为字符串的索引:

    with test as
    (select 'ABC' col1 from dual)
      select substr(col1, level, 1) result1
      from test
      connect by level <= length(col1);
    

    【讨论】:

    • 虽然它可以在行中工作,但它不能在多行中工作
    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多