Monday, July 2, 2012

Table name is not supported as bind variable in EXECUTE IMMEDIATE in PL/SQL

In DB2 PL/SQL , it does not support table name as bind variable in EXECUTE IMMEDIATE.

Like following :

create table A (c1 varchar2(100))

DB20000I  The SQL command completed successfully.

create or replace procedure proc1 (p1 varchar2(200),p2 varchar2(200)) IS t_sql varchar2(200); BEGIN t_sql := 'insert into :x values (:y)'; execute immediate t_sql using p1,p2;end

DB20000I  The SQL command completed successfully.

call proc1 ('a','b')
SQL0104N  An unexpected token ":x" was found following "insert into ".
Expected tokens may include:  "<insert_target>".  SQLSTATE=42601


Solution :

Solution is to replace the bind variable with variable name :

create or replace procedure proc1 (p1 varchar2(200),p2 varchar2(200)) IS t_sql varchar2(200); BEGIN t_sql := 'insert into ' || p1 || ' values (:y)'; execute immediate t_sql using p2;end

DB20000I  The SQL command completed successfully.

call proc1 ('a','b')
  Return Status = 0

select * from a
C1
----------------------------------------------------------------------------------------------------
b

  1 record(s) selected.