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.
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With