Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid table name error while using Execute Immediate statement with bind variables

I'm trying to get this dynamic SQL running ( using EXECUTE IMMEDIATE)

M_SQL_STATEMENT := 'SELECT MAX(:m_var1)+1 from :m_var2 RETURNING MAX(:m_var1)+1 INTO :m_var3';

EXECUTE IMMEDIATE M_SQL_STATEMENT
   USING M_COLUMN_NAME, UPPER(P_TABLE_NAME), M_COLUMN_NAME
   RETURNING INTO M_SEQ_NUMBER;

However, when trying to run this, I keep running into

ORA-00903: Invalid table

P_TABLE_NAME is a table name which is accepted as an input. I have confirmed that the table name & the column name are valid. I can't figure out why Oracle is throwing the error.

FWIW Altering the SQL statement to

M_SQL_STATEMENT := 'SELECT MAX(:m_var1)+1 SEQ from :m_var2 RETURNING SEQ INTO :m_var3';

still results in the same error.

like image 598
Sathyajith Bhat Avatar asked Mar 10 '11 12:03

Sathyajith Bhat


People also ask

How pass variable in execute immediate in Oracle?

Quotes and execute immediate When executing a string variable that contains quotes it is important to "escape" the quote marks. sqlstring := q'{insert into x values( ' || i || ')}'; execute immediate sqlstring; As we see, the Oracle EXECUTE IMMEDIATE statement can be used to execute dynamic SQL statements.

What type of SQL statement must you use execute immediate?

The EXECUTE IMMEDIATE statement executes a dynamic SQL statement or anonymous PL/SQL block. You can use it to issue SQL statements that cannot be represented directly in PL/SQL, or to build up statements where you do not know all the table names, WHERE clauses, and so on in advance.

How do you execute a query stored in a variable in Oracle?

You could do it in plain SQL with a SELECT statement. But, if you are really doing it in PL/SQL, then you need to (ab)use EXECUTE IMMEDIATE. Also, you would want to retrieve the output of the SELECT statement in PL/SQL, for which Oracle expects an INTO clause.

Can we use execute immediate for SELECT statement?

EXECUTE IMMEDIATE defines a select loop to process the retrieved rows. If your program does not know the data types of the SELECT statement result columns, use the EXECUTE IMMEDIATE statement with the USING clause to execute the select.


1 Answers

You need to put the table name and column name into the dynamic SQL, so something like

M_SQL_STATEMENT := 'SELECT MAX(' || M_COLUMN_NAME || ')+1 from ' 
|| P_TABLE_NAME';

EXECUTE IMMEDIATE M_SQL_STATEMENT INTO M_SEQ_NUMBER;
like image 61
Greg Reynolds Avatar answered Oct 18 '22 00:10

Greg Reynolds