Embeded SQL
Embeded SQL
Overview
Embedded SQL in DB2
An Introduction
DB2-DM-1
Host Languages
COBOL
PL/1
C
Assembler
FORTRAN
Embedded SQL
DB2-AP-2
DELIMITING SQL Statements
Coding SQL statements in a COBOL application requires beginning and ending delimiters
Whether or not a period is required after the END – EXEC is based on the logic of the
COBOL coding.
FORMAT
EXEC SQL
an SQL statement
END – EXEC.
SQL COMMUNICATION ARE (SQLCA)
The return code placed in the field SQLCODE indicates the success, failure or
execution encountered
DECLARING SQLCA
EXEC SQL
INCLUDE SQLCA
END-EXEC.
SQLCA FIELDS AND THEIR PURPOSE
One (or more) of these is set when an SQL statement is executed, and something out of
the ordinary is detected by DB2.
SQLWARN0 Set to a ‘W’ when one of the other flags is also set to a ‘W’
SQLWARN1 Set to a ‘W’ when column values are truncated being placed
into a host variable
SQLWARN2 Set to a ‘W’ when a NULL value was eliminated from any
built-in-functions.
Are just regular COBOL data items when used in a non – SQL COBOL
statement
VARCHAR(n) 01 var .
49 var1 PIC S9(04) COMP.
49 var2 PIC X(n) .
HOST VARIABLES
EXEC SQL
SELECT HIREDATE’
INTO :HV – HIREDATE : IV – HIREDATE
FROM EMPLOYEE
WHERE EMPNO = :HV – EMPNO
END – EXEC.
01 H-STRUCTURE.
02 HV-EMPNO PIC..
02 HV-HIREDATE PIC..
02 HV-SALARY PIC..
01 I-STRUCTURE.
02 IV PIC S9(4) COMP
OCCURS 3 TIMES.
EXEC SQL
SELECT EMPNO, HIREDATE, SALARY
INTO :H-STRUCTURE:I-STRUCURE
FROM EMPLOYEE
WHERE EMPNO = :HV-EMPNO
END-EXEC.
DECLARING DB2 TABLES
Coding the table declaration directly, using the DECLARE TABLE statement
EXEC SQL
DECLARE TDEPT TABLE
(DEPT NO CHAR(3) NOTNULL,
DEPTNAME VARCHAR(36) NOTNULL,
MGRNO CHAR(6) NOTNULL,
ADMRDEPT CHAR(3) NOTNULL)
END-EXEC.
Using DCLGEN (Declare Generation) to generate the table declaration and table
copying the same into the program in the WORKING-STORAGE SECTION using the
INCLUDE statement
EXEC SQL
INCLUDE DCLDEPT
END-EXEC.
DCLGEN
EXEC SQL
SELECT EMPNO, SALARY
INTO :HV-EMPNO, :HV-SALARY
FROM EMPLOYEE
WHERE EMPNO =:HV-EMPID
END-EXEC.
* Each evaluation of the statement returns at most ONE row from the
table EMPLOYEE
* DB2 places the retrieved data directly into the host variables
Note One can include the INTO clause in a select statement and set
up host variables to receive data directly from DB2 only when
the SELECT returns at most one row at a time.
HANDLING EXCEPTIONAL CONDITIONS
EXEC SQL
WHENEVER {SQLWARNING {GOTO LABEL
/SQLERROR /GOTO LABEL
/NOT FOUND} /CONTINUE}
END – EXEC.
EXAMPLE
IF SQLCODE = 100
PERFORM OUTPUT – ROUTINE.
IF SQLWARN1 = ‘W’
DISPLAY ‘VALUE US TRUNCATED’.
A SIMPLE DB2/SQL COBOL PROGRAM
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE1.
*
ENVIRONMENT DIVISION.
*
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-VARS.
05 CNAME PIC X(20).
05 FAT-NAME PIC X(20).
05 M-NAME PIC X(20).
05 DOB PIC 9(6).
05 STATE PIC X(10).
*
EXEC SQL
INCLUDE SQLCA
END-EXEC.
*
EXEC SQL
INCLUDE ORPHAN
END-EXEC.
A SIMPLE DB2/SQL COBOL PROGRAM
PROCEDURE DIVISION.
0001-MAIN-PARA.
DISPLAY “Enter the Name of the Child”.
ACCEPT CNAME.
DISPLAY “Enter the Child’s Father’s Name; Enter Blank if Unknown”.
ACCEPT FAT-NAME.
DISPLAY “Enter the Child’s Mother’s Name”.
ACCEPT DOB.
DISPLAY “Enter the State to which the Child belongs”.
ACCEPT STATE.
*
EXEC SQL
INSERT INTO ORPHAN (NAME,FNAME,MNAME,DOB,STATE)
VALUES(:CNAME,:FAT-NAME,:M-NAME, :DOB,:STATE)
END-EXEC.
IF SQLCODE = 0
DISLAY “RECORD ADDED”
ELSE
DISPLAY ‘ERROR OCCURRED”.
STOP RUN.
*
0001-MAIN-PARA-EXIT.
EXIT.
MULTIPLE-ROW TABLE MANIPULATION
EXEC SQL
SELECT *
FROM TDEPT
WHERE DEPTNO LIKE ‘D%’
END-EXEC.
* The rows are not ready for the application program to use because COBOL
manipulates data only one row at a time
* The CUROR facility allows a COBOL program to gain address ability to individual
row occurrences of a many-rows Result table.
* Names the cursor and its specific SELECT which, when the cursor is
OPENed, will retrieve a Result Table whose rows satisfy the WHERE
clause in the DECLARE CURSOR statement.
FORMAT
EXEC SQL
DECLARE cursor-name CURSOR FOR
SELECT column name list
FROM data source(s)
WHERE conditions to be met (if any)
[FOR UPDATE OF column name list
END-EXEC.
DECLARE CURSOR STATEMENT
EXAMPLE
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO,LASTNAME,JOBCODE
FROM EMPLOYEE
WHERE WORKDEPT=:HV-WORKDEPT
[FOR UPDATE OF JOBCODE]
END-EXEC.
The associated SELECT in this example returns all rows with WORKDEPT equal to
the value of the host variable HV-WORKDEPT;
* Besides the WHERE feature, the SELECT statement can utilize any or all of the
following SQL features:
Built-in Functions
HAVING clause
GROUP BY clause
ORDER BY clause
• If the SELECT within DECLARE CURSOR statement utilizes any of the following
features, the result table becomes ‘read-only’
UNION operator
DISTINCT keyword
GROUP BY clause
ORDR BY clause
HAVING clause
EXAMPLE
EXEC SQL
OPEN C1
END-EXEC.
* Returns a row from the Result Table to the program’s data area
FORMAT
EXEC SQL
FETCH cursor-name
INTO host-variable
END-EXEC.
EXAMPLE
EXEC SQL
FETCH C1
INTO :HV-EMPNO,:HV-JCOD
END-EXEC.
* Advances the cursor position to the next row of the Result Table
making it
the current row;
DB2 then retrieves data from the current row into the program
variables
FETCH STATEMENT
* If issued causing the cursor position to point after the last result table
row,
DB2 will set the SQLCODE field to + 100 and no data will be
transferred to the
host variables
CLOSE STATEMENT
* Tells the DB2 system that the accessing of the Result Table is
completed
EXAMPLE
EXEC SQL
CLOSE C1
END-EXEC.
* The cursor can be CLOSED at any time but it gets automatically CLOSED
when:
An Application Terminates
* All OPEND cursors will be CLOSED at the program termination, but a CLOSE
statement is recommended for performance reasons.
* The CLOSE statement should be executed for the previously OPENED cursors
only
A SKELETAL CURSOR PROGRAM
SEGMENT
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, JOBCODE
FROM EMPLOYEE
WHERE WORKDEPT=‘C01’
END-EXEC.
EXEC SQL
OPEN C1
END-EXEC.
EXEC SQL
FETCH C1
INTO :HV-EMPNO,:HV-JCOD
END-EXEC.
EXEC SQL
CLOSE C1
END-EXEC.
Intermediate Results
FETCH HV-EMPNO HV-JCOD
1 000030 60
2 000130 55
3 000140 56
A DB2/SQL COBOL PROGRAM WITH
CURSOR
Problem Definition
* To list the Name of the Child, its Date of Birth and the State to which
it belongs, for those orphans whose Father’s name is unknown
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE1.
*
ENVIRONMENT DIVISION.
*
DATA DIVISION.
WORKING – STORAGE SECTION.
01 WS-VARS.
05 CNAME PIC X(20).
05 FAT-NAME PIC X(20).
05 M-NAME PIC X(20).
05 DOB PIC 9(6).
05 STATE PIC X(10).
*
EXEC SQL
INCLUDE SQLCA
END-EXEC.
*
EXEC SQL
INCLUDE ORPHAN
END-EXEC.
A DB2/SQL COBOL PROGRAM WITH CURSOR
*
EXEC SQL
DECLARE NOPOP CURSOR FOR
SELECT NAME, DOB, STATE
FROM ORPHAN
WHERE FNAME =‘’
END-EXEC.
*
PROCEDURE DIVISION.
0001-MAIN-PARA.
EXEC SQL
OPEN CURSOR NOPOP
END-EXEC.
PERFORM 0011-CULL-PARA UNTIL SQLCODE = 100.
EXEC SQL
CLOSE NOPOP
END-EXEC.
STOP RUN.
A DB2/SQL COBOL PROGRAM WITH CURSOR
0001-MAIN-PARA-EXIT.
EXIT.
0011-CULL-PARA
EXEC SQL
FETCH NOPOP
INTO :CNAME, :DOB, :STATE
END-EXEC.
* Precompile
* Bind
PRE-COMPILER
SQL statements are commented out in source and replaced with the host language
caLL
statement.
DB2 precompile timestamps the DBRM modules and the program source code. This
timestamp is passed down to the program load module, and is also tied to the plan
by the DB2 catalog.
A Data Base Request Module (DBRM) that will be used later when the program
goes to the BIND process is created
BIND
Info about DB2 tables, indexes, etc.
DBRM1
SYSIBM.SYSTABLESPACE
*Bind
determines SYSIBM.SYSTABLES
SYSIBM.SYSCOLUMNS
access paths in the Extracted SQL statements SYSIBM.SYSINDEXES
from program SYSIBM.SYSCOLDIST
following ways:
D Data access strategy (plan)
• Identifying which
indexes will be used
B
• Defining sorting DBRM2 DB2 DIRECTORY
BIND DBRM2
B DB2 DIRECTORY
DSNDB01.SCT02
*Has an its objective the creation of an
Application Access Plan in the DB2 2 Information about bind
environment.
Package List
*Analyzing the DBRMs, it develops an DB2 CATALOG
Application Access plan based on the SYSIBM.SYSDBRM
access SYSIBM.SYSPLAN
SYSIBM.SYSPLANAUTH
requested and the database SYSIBM.SYSPLANDEP
SYSIBM.SYSPACKLIST
components present. SYSIBM.SYSPLSYSTEM
SYSIBM.SYSSTMT
SYSIBM.SYSPACKAUTH
*This plan is retrieved and executed SYSIBM.SYSTABAUTH
Optimizer
every time the program is run
PREPARING A DB2/SQL COBOL PROGRAM FOR
EXECUTION
PACKAGE
* Produced by binding the DBRMs
* Consists of a set of internal structures, representing the compiled
from of the original SQL statements in the corresponding DBRMs
* Physically stored in the DB2 directory
COLLECTION
* Is an optimizing compiler
* Converts high-level database requests (SQL statements) into optimized
internal
form
* Compiles SQL statements into “CODE” even though that code is not
true machine code per se
Code Set of internal control structures, that are used to drive a set of
generalized I/O routines within the Data Manager
* Has as its input, a DBRM and as its output, a package (the compiled
form of that DBRM)
* BINDs a given DBRM to produce a Package
* BINDs together a list of packages to produce an Application Plan or
simply plan
DB2 is thus a compiling system and Bind perform a compiling function for
SQL statements, much as the host language compiler provides a compiling
function for the host language statements in which those SQL statements are
embedded
PREPARING A DB2/SQL COBOL PROGRAM FOR
EXECUTION
Syntax Checking
* Bind examines the SQL statements in the input DBRM, parses them, and reports on
any syntax errors it finds.
Note Even though the Precompiler has already performed similar checks, as the
Precompiler is decoupled from the rest of DB2, Bind can’t assume that its input is a valid
precompiler output – the user might have constructed an invalid DBRM via some other
mechanism
The Precompiler can run even when DB2 is not available. It can even run on a
different machine – and its output is not automatically protected.
* Validates all the tables, views, and columns used in the program
* If any of the above objects is not present in the DB2 system, the BIND process will
terminate abnormally
PREPARING A DB2/SQL COBOL PROGRAM FOR
EXECUTION
Optimization
* Bind includes an Optimizer as an important subcomponent
* The optimizer chooses, for each SQL statement it processes, an optional access
strategy for
implementing that statement
Note Data manipulation statements such as SELECT specify only what data the user,
wants, not how to get
to that data;
The access path for getting to that data will be chosen by the optimizer. Programs
are thus independent of such access paths.
* Even in a very simple case, there could be at least two ways of performing the
desired retrieval. The optimizer will choose one of the two available strategies to adopt
* In general, the optimizer will make its choice on the basis of such considerations as
the following:
- Which tables are referenced in the SQL statement?
- How big those tables are?
- How selective those indices are?
- How the data is physically clustered on the disk?
- The form of the data WHERE clause in the request and so on.
Optimization
* Bind will generate code that is tightly bound to the optimizer's choice of strategy
Eg If the optimizer decides to make use of an index called X, then the generated
package will include explicit references to index X
How does it know how big the tables are, or what indexes exist?
A This information is kept in the catalog, in the form of database statistics. A special
utility, RUNSTATS is provided for gathering such statistics and storing them in the
catalog for the optimizer’s use
Package Generation
Verifying Authorization
* Checks whether the user who is to be the owner of the bound package is
allowed
Plan Bind
* Has as its input, a list of packages and/or package collections and as its
output, the bound application plan
* Also does some authorization checking. Specifically, it checks that the user
who is to be
the owner of the bound plan is authorized to execute all of the applicable
packages
FINAL EXECUTION
* Since the original program has now effectively been broken into two
pieces (Load Module and Application Plan), those two pieces must
somehow be brought back together again at execution time
* First, the COBOL load module is loaded into memory; it starts to
execute in the usual way
* Sooner or later it reaches the first call to the DB2 Languages Interface
module. That module gets control and passes control in turn to the
Runtime Supervisor
DATA MANAGER
* Is the component that manages the physical databases by performing all of
the normal access method functions like search, retrieval, update, index
maintenance.
* Invites other system components as necessary in order to perform detailed
functions as locking, logging, I/O operations, etc. during the performance of
its basic task
BUFFER MANAGER
* Is the component responsible for physically s data between external storage
and memory
* Employs sophisticated techniques such as read-ahead buffering and look-
aside buffering to get the best performance out of the buffer pools under its care
and to minimize the amount of physical I/O actually performed.