0

I want to create PL/SQL function recieves table name and column name and condition and then return one value from the table his name was passed in the parameter.

I have created the function like this:

create or replace function get_dynamic
  (tbl_name nvarchar2,col_name nvarchar2 ,cond nvarchar2 )
return nvarchar2 is
  res nvarchar2(30);
  code varchar2(500):='begin select :col_name into :res from :tbl_name where :cond; end;';
begin
  EXECUTE IMMEDIATE code using in col_name , out res , in tbl_name, in cond;
  return res;
end;

the function created without any problem BUT when I call the function using this code:

begin
    DBMS_OUTPUT.PUT_LINE(get_dynamic('EMPLOYEES', 'FIRST_NAME', 'EMPLOYEE_ID=100'));
end;

I get his Error:

ERROR at line 1:
ORA-06550: line 1, column 51:
PL/SQL: ORA-00903: invalid table name ORA-06550: line 1, column 7:
PL/SQL: SQL Statement ignored ORA-06512: at "HR.GET_DYNAMIC", line 7 ORA-06512: at line 2

although the table name, column name and condition all are correct.

Help Please!..

1 Answer 1

4

You cannot use bind variables to construct SQL statement. You can use it for passing data only. Rewrite your procedure in this way:

create or replace function get_dynamic
  (tbl_name nvarchar2,col_name nvarchar2 ,cond nvarchar2 )
return nvarchar2 is
  res nvarchar2(30);
  code varchar2(500):='begin select '||col_name||' into :res from '||tbl_name||' where '||cond||'; end;';
begin
  EXECUTE IMMEDIATE code using out res;
  return res;
end;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.