tags:

views:

47

answers:

2

My dynamic sql below to alter a table & create columns based on the output of a query is giving error.

Query :

DECLARE
   CURSOR c1 is select distinct WP_NO from temp;
   cnum VARCHAR2(255);

BEGIN

  FOR cnum in c1 
  LOOP
    EXECUTE IMMEDIATE 'Alter table temp_col add (:1 varchar2(255))' using cnum;
  END LOOP;  

  COMMIT;

END;

Error :

PLS-00457: expressions have to be of SQL types

+3  A: 

Try without using the bind variable:

DECLARE
  CURSOR c1 is select distinct WP_NO from temp;
  cnum VARCHAR2(255);

BEGIN

  FOR cnum in c1 
  LOOP
    EXECUTE IMMEDIATE 'Alter table temp_col add ('|| cnum ||' varchar2(255))';
  END LOOP;  

  COMMIT;

END;
OMG Ponies
exactly. Bind variables are not allowed everywhere.
ammoQ
Depending on the source of `temp.WP_NO` aka `cnum`, you may want to sanitize it to protect against SQL injection attacks.
Shannon Severance
A: 

You have a conflict with the cnum symbol, which you use both as a local variable and for the current row of the cursor.

You probably want this:

DECLARE
   CURSOR c1 is select distinct WP_NO from temp;

BEGIN

  FOR current_row in c1 
  LOOP
    EXECUTE IMMEDIATE 'Alter table temp_col add (:1 varchar2(255))' using current_row.WP_NO;
  END LOOP;  

  COMMIT;

END;

As you can see, you don't need to declare the *current_row* variable that you use in the for loop.

Codo
Bind variables cannot be used here.
Jeffrey Kemp
Both the answers did not work (though OMG ponies was right about the bind variables). The correct solution is :begin FOR x in (select distinct WP_NO from temp) loop execute immediate 'alter table temp_col add '|| x.wp_no || ' varchar2(255)'; END LOOP; END;
Sam