Pass (comma separated) -yet single parameter to cursor

cursorsoracleplsql

I have to get selection for a given string (with comma separated values) passed to the cursor. There can be multiple values that could be passed via single variable. My code is somewhat like:

CURSOR My_Cursor( vsStr1 )
  IS
  SELECT some_field
    FROM some_table
   WHERE txtfield1 IN ( vsStr1 );    --this field is varchar2 type

vsStr1 varchar2(100) := '01, 25, 80, 100';

How to pass that variable correclty? Any help would be appreciated.

Best Answer

The simplest little dirty trick I know for this is xmltable(). With xmltable()you can convert a comma-seperated list of values into rows, for example:

select * from xmltable('1, 2, 3')

COLUMN_VALUE
------------
1
2
3

Notice how the column is named column_value automatically. This is an XMLType column, that you need to convert to be able to compare it with your regular types, for example (column_value).getnumberval() or (column_value).getstringval()

Now using this, a cursor could be coded like this:

set serveroutput on
declare
  l_parameters varchar2(50) := '101, 102, 103, 104';

  cursor my_cursor (params varchar2)
  is
  select employee_id, first_name, last_name from hr.employees
  where employee_id in
    (select (column_value).getnumberval() from xmltable(params));
begin
  for c in my_cursor(l_parameters) loop
    dbms_output.put_line(c.employee_id || ': ' || c.first_name || ', ' || c.last_name);
  end loop;
end;
/

101: Neena, Kochhar
102: Lex, De Haan
103: Alexander, Hunold
104: Bruce, Ernst