Every PL/SQL
will be first compiled before execution. Compilation here involves, both syntax checks of PL/SQL constructs and semantic checks over the SQLs being used.
Running SQLs via EXECUTE IMMEDIATE means, the query is parsed and executed dynamically. And then we name it Dynamic SQL.The dynamic SQLs are formed using a string, and the query , hence is not known to Oracle before hand. And only during runtime, it is compiled and executed.
Whereas, in the other method, the SQL
is parsed for semantic checks during compilation itself. We call it as Static SQL. We get,all the invalid SQL statement errors during compilation itself.
The other main difference, would be, when a Static SQL is been used in a PROCEDURE
or FUNCTION
. Oracle would create a dependency of that table name with the Procedure
/function
. You can find them in the dba_dependencies table.
It is very important to create such dependencies because, when the table is being altered with modifying the column name that is referred in a function or the table/view/type itself is dropped, Then Oracle would INVALIDATE
the function. Thus making sure, we dont get unexpected Exceptions.But DYNAMIC sqls would be completely anonymous and have no dependencies created. You may get a ORA-942 TABLE OR VIEW DOESNOT EXISTS
error, only with DYNAMIC sql and not with a Static SQL, just because of this reason.
The below query would list out all the table names referred in the procedure or function, either as a Synonym(table referred cross schemas, without schema name) and tablename directly with schema name(or default schema)
select
proc_syn.referenced_owner,
proc_syn.referenced_name,
proc_syn.referenced_type,
syn_tab.table_name
from
dba_dependencies proc_syn, dba_synonyms syn_tab, dba_tables tables
where
proc_syn.name= 'YOUR_PROC'
AND REFERENCED_TYPE in ( 'SYNONYM','TABLE')
AND proc_syn.referenced_name = syn_tab.synonym_name
AND syn_tab.synonym_name = tables.table_name
AND syn_tab.owner = 'PUBLIC'
order by
proc_syn.referenced_owner, syn_tab.table_name;