PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T - SQL) Database Programming Instructor: Michael Kremer, Ph.D. Technology & Information Management Class 8
PROCEDURAL DATABASE PROGRAMMING
( PL/SQL AND T-SQL)
Database Programming
Instructor: Michael Kremer, Ph.D.Technology & Information Management
Class 8
AGENDA
10. Cursors
10.1 Cursor Basics
10.2 Cursor Parameters
10.3 Cursor Variables
10.4 Data Updates using Cursors
11. Dynamic SQL
11.1 Overview of Dynamic SQL
11.2 Basic Dynamic SQL
10.1 CURSOR BASICS
Cursor Runner (Latin), it runs through a result set
If possible, avoid cursors for the following reasons:
Cursors use a lot of overhead, often much more than an equivalent set-
based approach
Cursors override SQL Server’s built-in query optimizations, often making
them much slower than an equivalent set-based solution
In its simplest form, a cursor is a pointer to a result set
To create a cursor, you declare it like a variable and assign a SQL
Select statement to it
Then you open, fetch, and
eventually close it
209
10.1 CURSOR BASICS
Previous steps are generalized not exact syntax
Common terminology when working with cursors:
Static SQL: A SQL statement is static if it is fully specified, or fixed, at the
time the code containing that statement is compiled
Dynamic SQL: A SQL statement is dynamic if it is constructed at runtime
and then executed, so you do not completely specify the SQL statement in
the code you write
Result set: This is the set of rows identified by the database as fulfilling
the request for data specified by the SQL statement
210
10.1 CURSOR BASICS
Common terminology when working with cursors (continued):
Implicit cursor: The programming environment declares and manages an
implicit cursor every time you execute a SQL DML statement or a SELECT
that returns a single row from the database directly into a procedural data
structure
Explicit cursor: This is a SELECT statement that you declare as a cursor
explicitly in your application code
Cursor variable: This is a variable you declare that references or points to
a cursor object in the database
211
10.1 CURSOR BASICS
Opening Cursors
When you open a cursor, SQL statement is processed at that
time.
In Oracle, data is read at the time when the cursor is opened
(read-consistency model), even if changes occur afterwards. In
SQL Server, you can specify this behavior
Much simpler syntax in Oracle
Test whether cursor is
already open:
216
10.1 CURSOR BASICS
Fetching Cursors
A cursor is a pointer to a virtual table defined by the SELECT
statement
Fetching is the
process of
retrieving one row at a time
into your program’s current
scope and processing it
217
10.1 CURSOR BASICS
Use function @@FETCH_STATUS
to test whether there are
more rows to fetch
If you fetch past the last row, no exception is raised
Use the cursor attribute %FOUND or %NOTFOUND to test
whether a row was found or not
218
10.1 CURSOR BASICS
Closing Cursors
It is important to close a cursor in order to release system
resources
In Oracle, make sure to test whether a cursor is actually open
before you close it
219
10.1 CURSOR BASICS
Cursor Optimization Tips
Try to avoid using cursors whenever possible
Do not forget to close cursor when its result set is not needed
Do not forget to deallocate SQL Server cursor when the data structures
comprising the cursor are not needed
Try to reduce the number of records to process in the cursor
Try to reduce the number of columns to process in the cursor
Use READ ONLY cursors, whenever possible, instead of updatable cursors
Try avoid using insensitive, static and keyset cursors, whenever possible
Use FAST_FORWARD cursors, whenever possible
Use FORWARD_ONLY cursors, if you need updatable cursor and the
FETCH NEXT will be the only used fetch option
222
10.2 CURSOR PARAMETERS
To make your cursor more dynamic, add parameters to the
SELECT statement, mostly to the WHERE clause
Then pass a parameter into the program unit and use that
parameter to build the cursor dynamically
In SQL Server, you must use passed in
parameter directly in your SQL
statement
In Oracle, you add parameter to cursor
list declaration
Only when you open the cursor, you
pass in the parameter
That allows for further manipulation
of parameters in your program unit
223
10.2 CURSOR VARIABLES
A cursor variable is a variable that points to or references an
underlying cursor
Unlike an explicit cursor, which names a work area for the result
set, a cursor variable is a reference to that work area
The cursor variable can be opened for any query, even for
different queries within a single program execution
The most important benefit of the cursor variable is that it
provides a mechanism
for passing results of
queries between
different program units,
even between client and server programs
227
10.2 CURSOR VARIABLES
In Oracle, you have to declare a cursor type first
Then declare a cursorvariable
In SQL Server, a cursorvariable can only be usedas an OUTPUT mode
In Oracle, you can use a cursor variable for all modes, that is, IN, OUT, or IN OUT
Remember that the value of a cursor variable is the reference to the cursor object, not the state of the cursor object
In other words, the value of a cursor variable does not change after you fetch from or close a cursor
Only two operations, in fact, may change the value of a cursor variable (that is, the cursor object to which the variable points):
228
10.2 DATA UPDATES USING CURSORS
In general, cursors are used to read data mainly
When you issue a SELECT statement against the database to query some records, no locks are placed on the selected rows
There are times, however, when you will want to lock a set of records even before you change them in your program
FOR UPDATE clause
Oracle offers the FOR UPDATE clause of the SELECT statement to perform this locking
In SQL Server, you can use the FOR UPDATE clause only in a cursor
If you use multiple table SELECT statements, all tables involved are locked
When specifying individual columns, only rows in those tables referenced by these columns are locked
233
10.2 DATA UPDATES USING CURSORS
CURRENT OF clause
Oracle and SQL Server provide the WHERE CURRENT OF clause for both UPDATE and DELETE statements inside a cursor
This clause allows you to easily make changes to the most recently fetched row of data
Notice that the WHERE CURRENT OFclause references the cursor, not the record into which the next fetched row is deposited
To delete a row from the database for the most recently fetched record:
Most important advantage to using WHERE CURRENT OF to change the last row fetched is that you do not have to code in two (or more) places the criteria used to uniquely identify a row in a table
234
11.1 OVERVIEW OF DYNAMIC SQL
SQL statements that are constructed and executed at runtime
Use dynamic SQL sparingly and only when necessary (caching,
performance)
Applications of dynamic SQL:
Execute DDL statements
Support ad hoc query and update requirements of web-based
applications.
Softcode business rules and formulas.
Reporting requirements
Oracle: Old method package DBMS_SQL, newer method Execute
Immediate
SQL Server: Procedure sp_executesql, preferred way as it has an
interface (IN, OUT parameters)
Simpler method is Execute
239
11.1 OVERVIEW OF DYNAMIC SQL
Assume we have orders tables that are separated by year. The
year is appended to the table name, such as Orders2010,
Orders2011, etc.
Year is passed
as a parameter
Dynamically build
SQL statement.
Same concept applies to DDL statements:
240
11.2 BASIC DYNAMIC SQL
In Oracle, you can also use dynamic SQL in a cursor. This is
pretty powerful and represents ultimate flexibility
242