Oracle Dynamic SQL
Oracle Dynamic SQL
SQL
Moiz Lokhandwala
Business Learning Center
Business Learning
Satyam Confidential 1
Center
Objectives
Business Learning
Satyam Confidential 2
Center
Static SQL Statement Processing
C
o
m
p
i
l
e
T
i
m
e
Business Learning
Satyam Confidential 3
Center
Dynamic SQL Statement
Processing
Business Learning
Satyam Confidential 4
Center
Binding In PL\SQL
• Oracle needs values for any variables listed in the statement
for example:-
select empno,ename from emp where id=emp_id;
Oracle needs a value for emp_id. The process of obtaining these values is called
binding variables.
Business Learning
Satyam Confidential 5
Center
Binding In PL\SQL
• Static Binding
Binding at compile time, called static or early binding.
Increases efficiency
• Dynamic Binding
Binding at run time, called dynamic or late binding.
Increases flexibility
END;
Business Learning
Satyam Confidential 7
Center
Limitation
• Static SQL
• Data definition language (DDL) statements, such as CREATE, DROP, GRANT, and REVOKE.
• Session control language (SCL) statements, such as ALTER SESSION and SET ROLE.
Business Learning
Satyam Confidential 8
Center
Overcoming Limitation
• Dynamic SQL
• Provides Benefits
SQL statements reference valid database objects.
Necessary privileges are in place to access the database objects.
Performance of static SQL is generally better than dynamic SQL.
Business Learning
Satyam Confidential 10
Center
One More Example
• Table name is Unknown
• EXECUTE IMMEDIATE
• DYNAMIC CURSORS
• DBMS_SQL
Business Learning
Satyam Confidential 12
Center
Execute Immediate
The EXECUTE IMMEDIATE statement prepares (parses) and immediately
executes a dynamic SQL statement or an anonymous PL/SQL block.
EXECUTE IMMEDIATE dynamic_string
[INTO {define_variable[, define_variable]... | record}]
[USING [IN | OUT | IN OUT] bind_argument
[, [IN | OUT | IN OUT] bind_argument]...]
[{RETURNING | RETURN} INTO bind_argument[, bind_argument]...];
Dynamic_string
String expression that represents a SQL statement or PL/SQL block.
Define_variable
Stores a selected column value. Record is a user-defined or %ROWTYPE record that stores a selected row.
Input bind_argument
An expression whose value is passed to the dynamic SQL statement or PL/SQL block.
Output bind_argument
Variable that stores a value returned by the dynamic SQL statement or PL/SQL block.
• Record:-
begin
create record v_emo_rec (id varchar2(10),name varchar2(20));
• Returning …..into :-
declare
v_emp_name emp.emp_name%type;
begin
update emp set sal=sal*0.1 where emp_id=1000 returning emp_name into v_emp_name;
end;
Business Learning
Satyam Confidential 14
Center
Understand through Example.
DECLARE
sql_stmt VARCHAR2(200);
emp_id NUMBER(4) := 7566;
salary NUMBER(7,2);
emp_rec emp%ROWTYPE;
begin
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
sql_stmt := 'UPDATE emp SET sal = 2000 WHERE empno = :1 RETURNING sal INTO :2';
• You can place all bind arguments in the USING clause by default mode is IN.
• The INTO clause specifies the variables or record into which column values are retrieved. For each value
retrieved by the query, there must be a corresponding, type-compatible variable or field in the INTO clause.
• For DML statements that have a RETURNING clause, you can place OUT arguments in the RETURNING
INTO clause without specifying the parameter mode, which, by definition, is OUT.
• At run time, bind arguments replace corresponding placeholders in the dynamic string. So, every
placeholder must be associated with a bind argument in the USING clause and/or RETURNING INTO
clause
v_sql_tx:=' select '||colmn_name|| ' from '||table_name|| ' where '||cond_col||'='||cond_value; -- Use concatenation method
EXECUTE IMMEDIATE v_sql_tx INTO v_out_tx;
return v_out_tx;
end;
• Result:
o SGA is occupied with exactly the same statements.
select eName from emp where empNo=7896
select eName from emp where empNo=4564
select eName from emp where empNo=4546
o CPU time is spent re-parsing exactly the same statement.
Business Learning
Satyam Confidential 16
Center
The Solution
• Use bind variables
o Bind variables CAN only be used to supply values to be passed to SQL code.
o Bind variables are substituted with real values AFTER parsing
:bind1;
v_sql_tx:=' select '||colmn_name|| ' from '||table_name|| ' where '||cond_col||'='||
return v_out_tx;
end;
• You cannot bind in the names of schema elements (tables, columns, and so on) or chunks
of the SQL statement (such as the WHERE clause). For those parts of your string, you
must use concatenation.
Business Learning
Satyam Confidential 17
Center
Things To Know
• Dynamic SQL does not support any PL/SQL data types.
• For example, a reporting application in a data warehouse environment might not know the
exact table name until runtime. These tables might be named according to the starting month
and year of the quarter, for example INV_01_1997, INV_04_1997, INV_07_1997,
INV_10_1997, INV_01_1998, and so on. You can use dynamic SQL in your reporting
application to specify the table name at runtime.
• Within PL/SQL, you can execute any kind of SQL or PL/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.
EXECUTE IMMEDIATE 'BEGIN EVENT_HANDLER_' || to_char(event) || '(:1) ; END; ' USING param;
END;
• Multiple emp_location tables contain the employee information, where location is the name of city where the
office is located. For example, a table named emp_houston contains employee information for the company's
Houston office, while a table named emp_boston contains employee information for the company's Boston
office.
EMPNO ENAME JOB SAL DEPTN
1 Sameer Sales- 20000 O
12
2 Kailash Man
Executiv 25000 10
e
EXECUTE IMMEDIATE 'CREATE TABLE ' || 'emp_' || loc || '( empno NUMBER(4) NOT NULL, ename VARCHAR2(10),
job VARCHAR2(9), sal NUMBER(7,2), deptno
NUMBER(2) )';
END;
• The following function retrieves the number of employees at a particular location performing
a specified job:
CREATE OR REPLACE FUNCTION get_num_of_employees (loc VARCHAR2, job VARCHAR2) RETURN NUMBER
IS
query_str VARCHAR2(1000);
num_of_employees NUMBER;
BEGIN
query_str := 'SELECT COUNT(*) FROM ' || ' emp_' || loc || ‘ WHERE job = :job_title ';
RETURN num_of_employees;
END;
No
Yes
• Cursor variables are like C or Pascal pointers, which hold the memory
location (address) of some item instead of the item itself.
• In PL/SQL, a pointer has data type REF, where REF is short for REFERENCE
Therefore, a cursor variable has data type REF CURSOR..
• Cursor always refers to the same query work area, a Cursor variable can
refer to different work areas.
For example, the following procedure lists all of the employees with a particular job at a
specified location.
CREATE OR REPLACE PROCEDURE list_employees(loc VARCHAR2, job VARCHAR2)
IS
TYPE cur_typ IS REF CURSOR;
C cur_typ;
query_str VARCHAR2(1000);
emp_name VARCHAR2(20);
emp_num NUMBER;
BEGIN
query_str := 'SELECT ename, empno FROM emp_' || loc || ' WHERE job = :job_title';
-- find employees who perform the specified job
OPEN C FOR query_str USING job;
LOOP
FETCH C INTO emp_name, emp_num;
EXIT WHEN C%NOTFOUND;
-- process row here
END LOOP;
CLOSE C;
END;
• SQL – no semicolon at the end; must return the result into the variable of
corresponding type (if anything is returned):
• The DBMS_SQL package is a PL/SQL library that offers an API to execute SQL statements
dynamically.
• Programs that use the DBMS_SQL package make calls to this package to perform dynamic
SQL operations.
• The DBMS_SQL package has procedures to open a cursor, parse a cursor, supply binds, and
so on.
BIND_VARIABLE
BIND_ARRAY
DEFINE_COLUMN
DEFINE_ARRAY
EXECUTE_AND
_FETCH
COLUMN_VALUE
VARIABLE_VALUE
CLOSE_CURSOR
• VARIABLE_VALUE Procedure
Syntax
DBMS_SQL.VARIABLE_VALUE ( c IN INTEGER, name IN VARCHAR2, value OUT <datatype>);
Business Learning
Satyam Confidential 33
Center
DBMS_SQL Example
Business Learning
Satyam Confidential 34
Center
DBMS_SQL Example
Business Learning
Satyam Confidential 35
Center
Native Dynamic SQL Vs DBMS_SQL
Native Dynamic Sql DBMS_SQL
Native dynamic SQL is integrated with SQL The DBMS_SQL package is a PL/SQL library that offers an
API to execute SQL statements dynamically
Native dynamic SQL code is typically more compact and Equivalent code is more lengthy and complex.
readable
Programs that use native dynamic SQL are much faster than The DBMS_SQL package is based on a procedural API and
programs that use the DBMS_SQL package. Typically, native incurs high procedure call and data copy overhead.
dynamic SQL statements perform 1.5 to 3 times better than
equivalent DBMS_SQL calls.
Native Dynamic SQL Supports User-Defined Types The DBMS_SQL package does not support user-defined
objects, collections, and REFs.
Native dynamic SQL is not supported in client-side Programs. DBMS_SQL is Supported in Client-Side Programs
Native Dynamic Sql statements can’t be larger than 32KB. DBMS_SQL Supports SQL Statements Larger than 32KB
Native dynamic SQL prepares a SQL statement each time the DBMS_SQL Lets You Reuse SQL Statements.
statement is used, which typically involves parsing, The PARSE procedure in the DBMS_SQL package parses a
optimization, and plan generation. SQL statement once. After the initial parsing, you can use the
statement multiple times with different sets of bind arguments.
Business Learning
Satyam Confidential 37
Center
Unknowns
• What elements are involved?
– Example: The monthly summary table may not exist.
• What should be the search criteria?
– Example: Always one type of Search condition require?
Business Learning
Satyam Confidential 38
Center
Where To Use Dynamic
SQL
• Many types of applications need to use dynamic queries
Example:-
o Applications that query a database where new tables are created often
Business Learning
Satyam Confidential 39
Center
Questions & Open
Discussions