oracle pl/sql 分隔逗号

来源:互联网 发布:agv磁条算法 编辑:程序博客网 时间:2024/05/21 21:34

   经常会遇到分隔字符串的需求,如下面的例子,要想看懂这个例子,需要明白函数instr:

drop table test;

create table test(
  id number,
  codes varchar2(500)
);
insert into test values(1,'11,22,33,44');
insert into test values(2,'33,44,55,66');
insert into test values(3,'55,66,77,88');
commit;

declare
cursor c_row is select id,codes from test;
    j INT;
    i INT;
    len INT := 0;
    len1 INT := 0;
    str VARCHAR2 (4000);
    p_str VARCHAR2 (4000);
begin      
  for row_test in c_row loop  
  p_str :=row_test.codes;
  len := LENGTH (p_str);
  len1 := LENGTH (',');
  j :=0;
  i :=1;
    WHILE j < len
    LOOP  
        j := INSTR (p_str, ',', i);
        IF j = 0
          THEN
            j := len;
            str := SUBSTR (p_str, i);
            dbms_output.put_line('id:'||row_test.id||'  code:'||str);
            IF i >= len
            THEN  EXIT;
        END IF;
        ELSE
            str := SUBSTR (p_str, i, j - i);
            i := j + len1;
            dbms_output.put_line('id:'||row_test.id||'  code:'||str);
        END IF;
     END LOOP;
  end loop;
end; 
/

id:1  code:11
id:1  code:22
id:1  code:33
id:1  code:44
id:2  code:33
id:2  code:44
id:2  code:55
id:2  code:66
id:3  code:55
id:3  code:66
id:3  code:77

id:3  code:88


instr( string1, string2, start_position,nth_appearance ) 
string1  
源字符串,要在此字符串中查找。
string2  要在string1中查找的字符串 。
start_position  代表string1 的哪个位置开始查找。此参数可选,如果省略默认为1. 字符串索引从1开始。如果此参数为正,从左到右开始检索,如果此参数为负,从右到左检索,返回要查找的字符串在源字符串中的开始索引。
nth_appearance 代表要查找第几次出现的string2. 此参数可选,如果省略,默认为 1.如果为负数系统会报错。

0 0