Oracle の ty_str_split + MySQL の proc_split

oracle实现字符串分割

功能描述:用指定分隔符切割输入的字符串,返回一维数组,每个数组元素为一个子串。

 1 CREATE OR REPLACE TYPE ty_str_split IS TABLE OF VARCHAR2 (4000);
 2 
 3 CREATE OR REPLACE FUNCTION fn_split (p_str IN VARCHAR2, p_delimiter IN VARCHAR2)
 4   RETURN ty_str_split
 5 IS
 6   j INT := 0;
 7   i INT := 1;
 8   len INT := 0;
 9   len1 INT := 0;
10   str VARCHAR2 (4000);
11   str_split ty_str_split := ty_str_split ();
12 BEGIN
13   len := LENGTH (p_str);
14   len1 := LENGTH (p_delimiter);
15 
16   WHILE j < len
17   LOOP
18     j := INSTR (p_str, p_delimiter, i);
19 
20     IF j = 0
21     THEN
22         j := len;
23         str := SUBSTR (p_str, i);
24         str_split.EXTEND;
25         str_split (str_split.COUNT) := str;
26 
27         IF i >= len
28         THEN
29           EXIT;
30         END IF;
31     ELSE
32         str := SUBSTR (p_str, i, j - i);
33         i := j + len1;
34         str_split.EXTEND;
35         str_split (str_split.COUNT) := str;
36     END IF;
37   END LOOP;
38 
39   RETURN str_split;
40 END fn_split;
41 /

测试

DECLARE
  CURSOR c
  IS
    SELECT *
      FROM TABLE (CAST (fn_split ('1;;12;;123;;1234;;12345', ';;') AS ty_str_split
                  )
              );

  r c%ROWTYPE;
BEGIN
  OPEN c;

  LOOP
    FETCH c INTO r;

    EXIT WHEN c%NOTFOUND;
    DBMS_OUTPUT.put_line (r.column_value);
  END LOOP;

  CLOSE c;
END;

 结果

http://blog.csdn.net/a9529lty/article/details/3810905

/************************************************************************/

mysql:

先说调用方法
call proc_split('a,b,c',',');
select * from splittable

存储过程

CREATE  PROCEDURE `proc_split`(
    inputstring varchar(1000),
      delim char(1)
)
      NOT DETERMINISTIC
      CONTAINS SQL
      SQL SECURITY DEFINER
      COMMENT ''
begin
      declare strlen int;
      declare last_index int;
      declare cur_index int;
      declare cur_char VARCHAR(200);
      declare len int;
      set cur_index=1;
      set last_index=0;
    set strlen=length(inputstring);
      drop temporary table if exists splittable;/**/
      create TEMPORARY table splittable(
            id int AUTO_INCREMENT,
            value VARCHAR(20),
            PRIMARY KEY (`ID`),
            UNIQUE KEY `ID` (`ID`)
      ) ;
      WHILE(cur_index<=strlen) DO     
      begin
            if substring(inputstring from cur_index for 1)=delim or cur_index=strlen then
              set len=cur_index-last_index-1;
              if cur_index=strlen then
                 set len=len+1;
              end if;
              insert into splittable(`value`)values(substring(inputstring from (last_index+1) for len));
                  set last_index=cur_index;
            end if;
            set cur_index=cur_index+1;
      END;
      end while;
end

自信与努力 用心坚持
原文地址:https://www.cnblogs.com/kyxyes/p/3474194.html