需求:函数传入一个字符串参数 例如 123-456
将这个字符串123-456拆成两个值 123 456,在通过两个值分别查出数据(例如 张三 李四),拼接成 张三-李四
--声明变量--
DROP TYPE STR_SPLIT; CREATE OR REPLACE TYPE str_split IS TABLE OF VARCHAR2 (4000); / DROP TYPE TYPE_SPLIT; CREATE OR REPLACE type type_split as table of varchar2(500); / --分割字符串函数-- CREATE OR REPLACE TYPE str_split IS TABLE OF VARCHAR2 (4000); CREATE OR REPLACE FUNCTION splitstr(p_string IN VARCHAR2, p_delimiter IN VARCHAR2) RETURN str_split PIPELINED AS v_length NUMBER := LENGTH(p_string); v_start NUMBER := 1; v_index NUMBER; BEGIN WHILE(v_start <= v_length) LOOP v_index := INSTR(p_string, p_delimiter, v_start); IF v_index = 0 THEN PIPE ROW(SUBSTR(p_string, v_start)); v_start := v_length + 1; ELSE PIPE ROW(SUBSTR(p_string, v_start, v_index - v_start)); v_start := v_index + 1; END IF; END LOOP; RETURN; END splitstr; --使用方法-- select * from table(splitstr('16021-16022','-')); --执行出的结果 COLUMN_VALUE 16021 16022 这个是我自己写的函数 CREATE OR REPLACE FUNCTION fn_GetDead (v_deadId varchar2) return varchar2 is v_deadString varchar2(100); v_deadString_all VARCHAR2(4000); cursor c_deadIdSpilt --设置一个分割字符串游标-- is select * from table(splitstr(''||v_deadId||'','-')); c_row c_deadIdSpilt%rowtype; begin if instr(v_deadId,'-') > 0 then ---判读变量中是否含有"-"字符,如果有,则循环遍历这个字符,取出亡人姓名 open c_deadIdSpilt; --打开游标-- loop fetch c_deadIdSpilt into c_row; EXIT WHEN c_deadIdSpilt%NOTFOUND; SELECT wrxm into v_deadString FROM wrxxb WHERE id=C_ROW.COLUMN_VALUE; v_deadString_all:=v_deadString_all||'-'||v_deadString; end loop; close c_deadIdSpilt; return ltrim(v_deadString_all,'-'); else SELECT wrxm INTO v_deadString FROM wrxxb WHERE id=''||v_deadId||''; return v_deadString; end if; --异常处理-- exception when others then dbms_output.put_line('error'); return -1; end fn_GetDead; / --调用-- SELECT fn_GetDead('16021-16022') FROM dual; --我执行出的结果-- FN_GETDEAD('16021-16022') 马瑞祥-赵桂芝