Oracle PL/SQL - Using Bind Variables in Dynamic SQL

Description

Using Bind Variables in Dynamic SQL

Demo

SQL>
SQL>--  w w  w.j av a 2  s .  c  om
SQL> drop table emp;

Table dropped.
SQL> create table emp(
  2    empno    number(4,0),
  3    ename    varchar2(10),
  4    job      varchar2(9),
  5    mgr      number(4,0),
  6    hiredate date,
  7    sal      number(7,2),
  8    comm     number(7,2),
  9    deptno   number(2,0)
 10  );

Table created.
SQL>
SQL> insert into emp values(7839, 'KING', 'PRESIDENT', null, to_date('17-11-1981','dd-mm-yyyy'), 5000, null, 10);
SQL> insert into emp values(7698, 'BLAKE', 'MANAGER', 7839,to_date('1-5-1981','dd-mm-yyyy'), 2850, null, 30);
SQL>
SQL> create or replace function f_getEmp_tx
  2               (i_empNo NUMBER, i_column_tx VARCHAR2)
  3   return VARCHAR2
  4   is
  5        v_out_tx VARCHAR2(2000);
  6        v_sql_tx VARCHAR2(2000);
  7  begin
  8        v_sql_tx :=
  9            'select '||i_column_tx||
 10            ' from emp ' ||
 11            'where empNo=:var01';
 12        execute immediate v_sql_tx
 13        into v_out_tx
 14        using i_empNo;
 15        return v_out_tx;
 16   exception
 17        when others then return null;
 18  end;
 19  /

Function created.

Related Topic