基于垂直线分隔符

时间:2015-12-05 09:41:10

标签: variables plsql oracle11g split oracle-sqldeveloper

我有以下plsql代码

DECLARE
   v_personal_info VARCHAR2(100);
   v_name VARCHAR2(100);
   v_signature VARCHAR2(100);
   CURSOR c_personal_info
   IS
     select personal_info from users where name is not null;
BEGIN
  FOR lr_row IN c_personal_info
  LOOP
    v_personal_info := lr_row.personal_info;
    -- Need to split v_personal_info based on |
  END LOOP;
END;
/

v_personal_info的典型值看起来像'Aniket Thakur | athakur',我需要将其拆分为不同的变量,例如

v_name := 'Aniket Thakur'
v_signature := 'athakur'

我该怎么办?是否存在基于预定义分隔符进行拆分的内置函数?

2 个答案:

答案 0 :(得分:1)

如果v_personal_info的值是统一的且始终是结构string_1 + | + string_2,那么您可以轻松使用REGEXP_SUBSTR

在这种情况下,您的程序可以写成如下:

DECLARE
   v_personal_info VARCHAR2(100);
   v_name VARCHAR2(100);
   v_signature VARCHAR2(100);
   CURSOR c_personal_info
   IS
     select personal_info from users where name is not null;
BEGIN
  FOR lr_row IN c_personal_info
  LOOP
    v_personal_info := lr_row.personal_info;
    v_name := REGEXP_SUBSTR ( v_personal_info, '^[^|]*');
    v_signature := REGEXP_SUBSTR (v_personal_info,'[^|]*$')
  END LOOP;
END;
/

当然,除非你在某处写下这些值,否则这个过程实际上并没有用。

但是,如果您想要一种使用不同分隔符分割字符串的通用方法,那么您将必须创建自己的函数。这里有多个例子可以做到这一点。见this& this

其中一位SO用户Split single comma delimited string into rows in Oracle

撰写了非常好的文章

答案 1 :(得分:0)

Hawks的回答很好,但我不想使用正则表达式,所以我使用简单的SUBSTRINSTR方法。

DECLARE
   v_personal_info VARCHAR2(100);
   v_name VARCHAR2(100);
   v_signature VARCHAR2(100);
   delimitIndex number;
   CURSOR c_personal_info
   IS
     select personal_info from users where name is not null;
BEGIN
  FOR lr_row IN c_personal_info
  LOOP
    v_personal_info := lr_row.personal_info;
    delimitIndex := INSTR(v_personal_info, '|');
    if delimitIndex != 0 then
        v_name := SUBSTR(v_personal_info, 1, delimitIndex - 1);
        v_signature := SUBSTR(v_personal_info, delimitIndex+1, LENGTH(v_personal_info)-delimitIndex);
    END if;
  END LOOP;
END;
/