How to create and insert into a table in an anonymous block

oracle-11g-r2plsql

I have PL/SQL anonymous block that creates a table (using execute immediate) and then inserts data into the table.

When the block compiles, it gives me an ORA-00942: table or view does not exist error.

Well, no, it doesn't exist, but it will be created before the insert occurs. If I create the table before compiling, it will work.

How can I handle this?

Best Answer

Generally, it doesn't make sense to create tables in anonymous blocks let alone to then insert data into those tables in the same anonymous block. Creating new objects at runtime is a bad idea (hopefully you're not trying to create a temporary table like you would with other databases).

If you really do need to create a new table at runtime, you can insert data in the same anonymous block only by using dynamic SQL for the INSERT operation as well. You would need to use dynamic SQL every time you referenced the newly created table in the same anonymous block. You could also create the table in one anonymous PL/SQL block and then insert the data in a second anonymous PL/SQL block. That would not require that the INSERT statement use dynamic SQL.

Since it sounds from the comments like you are trying to create a temporary table like you would in other databases, you probably want to take a look at this StackOverflow thread that discusses alternatives to creating temporary tables in Oracle.