Native Dynamic SQL
Native Dynamic SQL
This chapter shows you how to use native dynamic SQL (dynamic SQL for short), a PL/SQL
interface that makes your applications more flexible and versatile. You learn simple ways to
write programs that can build and process SQL statements "on the fly" at run time.
Within PL/SQL, you can execute any kind of SQL statement (even data definition and data
control statements) without resorting to cumbersome programmatic approaches. Dynamic SQL
blends seamlessly into your programs, making them more efficient, readable, and concise.
However, some programs must build and process a variety of SQL statements at run time. For
example, a general-purpose report writer must build different SELECT statements for the various
reports it generates. In this case, the full text of the statement is unknown until run time. Such
statements can, and probably will, change from execution to execution. So, they are called
dynamic SQL statements.
Dynamic SQL statements are stored in character strings built by your program at run time. Such
strings must contain the text of a valid SQL statement or PL/SQL block. They can also contain
placeholders for bind arguments. A placeholder is an undeclared identifier, so its name, to which
you must prefix a colon, does not matter. For example, PL/SQL makes no distinction between
the following strings:
'DELETE FROM emp WHERE sal > :my_sal AND comm < :my_comm'
'DELETE FROM emp WHERE sal > :s AND comm < :c'
To process most dynamic SQL statements, you use the EXECUTE IMMEDIATE statement. However,
to process a multi-row query (SELECT statement), you must use the OPEN-FOR, FETCH, and CLOSE
statements.
You want to execute a SQL data definition statement (such as CREATE), a data control
statement (such as GRANT), or a session control statement (such as ALTER SESSION). In
PL/SQL, such statements cannot be executed statically.
You want more flexibility. For example, you might want to defer your choice of schema
objects until run time. Or, you might want your program to build different search
conditions for the WHERE clause of a SELECT statement. A more complex program might
choose from various SQL operations, clauses, etc.
You use package DBMS_SQL to execute SQL statements dynamically, but you want better
performance, something easier to use, or functionality that DBMS_SQL lacks such as
support for objects and collections. (For a comparison with DBMS_SQL, see Oracle9i
Application Developer's Guide - Fundamentals.)