Nonu
Nonu

Reputation: 15

How to pass column name as parameter in a Stored Procedure in PL/SQL?

I want to pass something like p.lastname or p.first_name in the query_type parameter so that i can order by what i want; and accordingly, query_value would contain something like UPPER('%Smith%') or UPPER('%Henry%') depending on what i put in query_type.

But when I pass these as strings, the cursor is returned empty.

Any tips? I would ideally not want to get rid of the cursor.

ps. search_cursor has been declared as a REF CURSOR in package header.

PROCEDURE test_proc(
          company_id IN NUMBER,
          query_type IN VARCHAR2,
          query_value IN VARCHAR2,
          result_limit IN NUMBER,
          cur OUT search_cursor) AS
BEGIN

OPEN cur FOR
select *
from (SELECT p.first_name as "first_name",
             p.surname as "surname",
             row_number()
      OVER (ORDER BY query_type asc) rn
      FROM person p, company c
      WHERE c.employee_id = p.person_id
            AND c.id = company_id
            AND query_type LIKE query_value
      )

where rn BETWEEN 1 AND result_limit;

END test_proc;

Upvotes: 0

Views: 734

Answers (1)

Littlefoot
Littlefoot

Reputation: 142710

Dynamic SQL. Beware of SQL injection.

As I don't have your tables, I used Scott's sample schema.

Function that returns ref cursor (that's what you do as well, only as procedure's OUT parameter):

SQL> create or replace function f_test
  2    (query_type  in varchar2,
  3     query_value in varchar2
  4    )
  5    return sys_refcursor
  6  is
  7    l_str varchar2(500);
  8    rc    sys_refcursor;
  9  begin
 10    l_str := 'select e.ename, e.job, ' ||
 11             '  row_number() over (order by ' || query_type || ' asc) rn ' ||
 12             'from emp e join dept d on e.deptno = d.deptno ' ||
 13             'where ' || query_type || ' like ' || query_value;
 14    open rc for l_str;
 15    return rc;
 16  end;
 17  /

Function created.

Testing:

SQL> select f_test('e.ename', q'[upper('%King%')]') from dual;

F_TEST('E.ENAME',Q'[
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

ENAME      JOB               RN
---------- --------- ----------
KING       PRESIDENT          1


SQL>

Upvotes: 1

Related Questions