Wednesday, October 15, 2008

Oracle PL/SQL Split Function Boosts WHERE IN Clause Usability

Big thanks to Tech Republic for an article about creating a SPLIT user-defined function that accepts a delimited string and creates a table with N rows of data:




function Split
(
p_list varchar2,
p_del varchar2 := ','
) return split_tbl pipelined
is
l_idx pls_integer;
l_list varchar2(32767) := p_list;
l_value varchar2(32767);
begin
loop
l_idx := instr(l_list,p_del);
if l_idx > 0 then
pipe row(substr(l_list,1,l_idx-1));
l_list := substr(l_list,l_idx+length(p_del));
else
pipe row(l_list);
exit;
end if;
end loop;
return;
end split;


 

And here’s how I used it to perform a “dynamic” query passing in a list of values:




select *
from myTable
where IN_VARCHAR_LIST IS NULL OR
APP.AGENCY_ID IN(
select column_value
from table(Split(IN_VARCHAR_LIST)))


1 comment:

Anonymous said...

Brilliant, big thanks for your help!