Oracle字符串分割Split
Oracle字符串分割Split
一、创建数组类型
Sql代码
CREATE OR REPLACE TYPE T_RET_TABLE IS TABLE OF VARCHAR2(512)
二、创建字符串分割函数
Sql代码
CREATE OR REPLACE FUNCTION F_SPLIT_STRING(AS_STR VARCHAR2,
AS_SPLIT VARCHAR2)
RETURN T_RET_TABLE IS
-- Author : Guomm
-- Created : 2013/5/22 13:38:46
-- Purpose : 字符串分割
-- Params
-- AS_STR : 要处理的字符串
-- AS_SPLIT :字符串分割符
V_OUT T_RET_TABLE;
V_TMP VARCHAR2(4000);
V_ELEMENT VARCHAR2(4000);
BEGIN
V_TMP := AS_STR;
V_OUT := T_RET_TABLE();
--如果存在匹配的分割符
WHILE INSTR(V_TMP, AS_SPLIT) > 0 LOOP
V_ELEMENT := SUBSTR(V_TMP, 1, INSTR(V_TMP, AS_SPLIT) - 1);
V_TMP := SUBSTR(V_TMP,
INSTR(V_TMP, AS_SPLIT) + LENGTH(AS_SPLIT),
LENGTH(V_TMP));
V_OUT.EXTEND(1);
V_OUT(V_OUT.COUNT) := V_ELEMENT;
END LOOP;
IF V_TMP IS NOT NULL THEN
V_OUT.EXTEND(1);
V_OUT(V_OUT.COUNT) := V_TMP;
END IF;
RETURN V_OUT;
END F_SPLIT_STRING;
OK,到此功能已经实现,
三、调用
Sql代码
SELECT * FROM TABLE(F_SPLIT_STRING('1,2,3,4,5,6',','))
DECLARE
V_ARRAY T_RET_TABLE;
BEGIN
V_ARRAY := F_SPLIT_STRING('1,2,3,4,5,6',',');
FOR I IN 1..V_ARRAY.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(V_ARRAY(i));
END LOOP;
END;