GouthamAnand
asked on
how to fetch the values from a string separated by commas in Oracle pl/sql
I need to load the values arun, kiran and raj in a table also can you please let me know how can I use this string in IN clause of an sql?
like select * from emp where emp name in (v_values)
somthing like this?
like select * from emp where emp name in (v_values)
somthing like this?
v_values varchar2(100):='arun,kiran,raj';
ASKER
Sorry I did not mention that I am using Oracle 8i. I think this work from Oracle 9i onwards. Can you please let me know the solution in oracle 8i.
create or replace type varchar2_tab as table of varchar2(30)
/
CREATE OR REPLACE FUNCTION str2tbl(
p_string IN VARCHAR2,
p_delimiter IN VARCHAR2 DEFAULT ','
)
RETURN varchar2_tab
AS
l_string LONG DEFAULT p_string || p_delimiter;
l_index INTEGER;
l_table varchar2_tab := varchar2_tab();
BEGIN
IF (p_string IS NULL)
THEN
RETURN l_table;
END IF;
IF (p_delimiter IS NULL)
THEN
FOR i IN 1..length(l_string)
LOOP
l_table.extend;
l_table(l_table.count) := trim(substr(l_string,i,1)) ;
END LOOP;
RETURN l_table;
END IF;
LOOP
l_index := instr(l_string,p_delimiter );
exit when (nvl(l_index,0) = 0);
l_table.extend;
l_table(l_table.count) := trim(substr(l_string,1,l_i ndex-1));
l_string := substr(l_string,l_index+le ngth(p_del imiter));
END LOOP;
RETURN l_table;
END str2tbl;
/
Now you can use the code:
select * from table(str2tbl('1,2,3,4,5,5 ,6,7'));
select * from table(str2tbl('phr_,bas_,e hf_'));
/
CREATE OR REPLACE FUNCTION str2tbl(
p_string IN VARCHAR2,
p_delimiter IN VARCHAR2 DEFAULT ','
)
RETURN varchar2_tab
AS
l_string LONG DEFAULT p_string || p_delimiter;
l_index INTEGER;
l_table varchar2_tab := varchar2_tab();
BEGIN
IF (p_string IS NULL)
THEN
RETURN l_table;
END IF;
IF (p_delimiter IS NULL)
THEN
FOR i IN 1..length(l_string)
LOOP
l_table.extend;
l_table(l_table.count) := trim(substr(l_string,i,1))
END LOOP;
RETURN l_table;
END IF;
LOOP
l_index := instr(l_string,p_delimiter
exit when (nvl(l_index,0) = 0);
l_table.extend;
l_table(l_table.count) := trim(substr(l_string,1,l_i
l_string := substr(l_string,l_index+le
END LOOP;
RETURN l_table;
END str2tbl;
/
Now you can use the code:
select * from table(str2tbl('1,2,3,4,5,5
select * from table(str2tbl('phr_,bas_,e
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much.
glad I could help
You may write your query as:
Select * from emp
where instr('arun,kiran,raj', empname || ',') > 0
the INSTR method only works if the string to be searched ends in ',' and if the substring has no commas (which may be a good assumption, but it's not universally true)
it also prevents any indexes on empname from being used.
it also prevents any indexes on empname from being used.
then write your query like this....
select * from emp where emp name in (select * from table(str2tbl(v_values)))
Open in new window