db2 applications
Post on 03-Apr-2018
221 Views
Preview:
TRANSCRIPT
-
7/28/2019 DB2 Applications
1/167
UNIT 1: DB2 PROGRAM PREPARATION
DB2 PROGRAM PREPARATION ..1.1
SQL STATEMENT FORMATS (DELIMITERS) 1.2DB2 DATA TYPES - CHARACTER DATA TYPE 1.3
GRAPHIC DATA TYPE 1.4
NUMERIC DATA TYPE 1.5
DATE / TIME DATA TYPES 1.6
NULL ATTRIBUTE 1.7
NULL ATTRIBUTE (Cont.) 1.8
(NOT NULL) WITH DEFAULT 1.9USER DEFINED DEFAULT VALUES 1.10
HOST VARIABLES 1.11
HOST VARIABLES (Cont.) 1.12
DB2 DATA TYPES VS HOST VARIABLES 1.13
HOST STRUCTURES 1.14
SELECTION OF A SINGLE ROW 1.15
COMPILERS DONT UNDERSTAND SQL 1.16
DB2 PROGRAM PREPARATION STEPS 1.17
PRECOMPILATION 1.18
DCLGEN COMMAND 1.19
-
7/28/2019 DB2 Applications
2/167
DCLGEN COMMAND (Cont.) 1.20
SQL INCLUDE STATEMENT SQLCA 1.21
DBRM 1.22DBRM (Cont.) 1.23
COMPILATION AND LINK-EDIT 1.24
BIND PACKAGE 1.25
BIND PACKAGE (Cont.) 1.26
PACKAGE 1.27
PACKAGE (Cont.) 1.28COLLECTIONS 1.29
APPLICATION PLAN 1.30
CONSISTENCY TOKENPROGRAM PREPARATION 1.31
LOCATING PACKAGES AT EXECUTION TIME 1.32
THE MISSING LINK 1.33
PLAN AND PACKAGES 1.34
BIND PLANPACKAGE LIST 1.35BIND PLAN DBRMS 1.36
-
7/28/2019 DB2 Applications
3/167
UNIT 2: DB2 INTERNALS
OVERVIEW 2.1
DATA STORAGE 2.2
DATA STORAGE (Cont.) 2.3
DATA STORAGE (Cont.) 2.4
DATA STORAGE (Cont.) 2.5NORMALIZATION 1-NF 2.6
NORMALIZATION 1-NF (Cont.) 2.7
NORMALIZATION 2-NF 2.8
NORMALIZATION 2-NF (Cont.) 2.9
NORMALIZATION 3-NF 2.10
NORMALIZATION 4-NF 2.11NORMALIZATION 5-NF 2.12
NORMALIZATION RECOMMENDATION 2.13
OPTIMIZER 2.14
OPTIMISER (Cont.) 2.15
DB2 CATALOG AND DIRECTORY 2.16
CATALOG STRUCTURE 2.17CATALOG STRUCTURE (Cont.) 2.18
CATALOG STRUCTURE (Cont.) 2.19
DB2 DIRECTORY 2.20
DATA LOCKING 2.21
LOCKING MECHANISM 2.22
LOCKS VS LATCHES 2.23DEADLOCKS AND TIMEOUTS 2.24
-
7/28/2019 DB2 Applications
4/167
UNIT 3 : CURSOR HANDLING
OVERVIEW 3.1
DEFINING CURSORS 3.2
DEFINING CURSORS (Cont.) 3.3
SAMPLE PROGRAM FOR CURSORS 3.4
CURSOR DECLARATION 3.5
UPDATING /DELETING WITH THE CURSORS 3.6READ-ONLY CURSORS 3.7
READ-ONLY CURSORS (Cont.) 3.8
-
7/28/2019 DB2 Applications
5/167
UNIT 4: DYNAMIC AND STATIC SQL
DYNAMIC SQL AND STATIC SQL 4.1
STATIC SQL 4.2
DYNAMIC SQL 4.3
DYNAMIC SQL (Cont) 4.4EXECUTE IMMEDIATE 4.5
EXECUTE IMMEDIATE (Cont) 4.6
NON-SELECT DYANMIC SQL 4.7
FIXED-LIST SELECT 4.8
FIXED-LIST SELECT (Cont) 4.9
VARYING-LIST SELECT 4.10SELECT STATEMENT WITH VARYING LIST 4.11
SELECT STATEMENT WITH VARYING LIST (Cont..) 4.12
SQL DESCRIPTOR AREA (SQLCA)FUNCTION 4.13
SQLDAFORMAT 4.14
SQLDACOLUMN DESCRIPTION 4.15
SQLDATechnique 1 4.16SQLDATechnique 1(Cont) 4.17
SQLDATechnique 2 4.18
SQLDA USAGESUMMARY 4.19
COMMIT AND ROLLBACK 4.20
COMMIT AND ROLLBACK (Cont..) 4.21
-
7/28/2019 DB2 Applications
6/167
UNIT 5: HANDLING NULLS AND ERRORS
HANDLING NULLS AND ERRORS 5.1
SQLCA LAYOUT 5.2
SQLSTATE 5.3SQLCA CODES 5.4
SQLCA CODES USAGE 5.5
ERROR HANDING 5.6
ERROR HANDING (Cont) 5.7
SCOPE OF WHENEVER 5.8
ERROR MESSAGE FORMATTING ROUTINE 5.9ERROR HANDLINGGENERAL 5.10
RETRIEVING NULL VALUES 5.11
INSERTING NULL VALUES 5.12
SELECTING NULL VALUES 5.13
HOST STRUCTUREINDICATOR VARIABLE 5.14
HOST STRUCTUREINDICATOR VARIABLE (Cont..) 5.15HANDLING ARITHMETIC ERRORS 5.16
HANDLING CONVERSION ERROR 5.17
ARITHMETIC AND CONVERSION ERROR EXAMPLES 5.18
EXAMPLE OF ARITHMETIC ERROR 5.19
INDICATOR VARIABLE VALUES 5.20
OTHER ERROR CONDITIONS 5.21
-
7/28/2019 DB2 Applications
7/167
UNIT 6: STORED PROCEDURES
STORED PROCEDURES OVERVIEW 6.1STORED PROCEDURES: FLOW 6.2
STORED PROCEDURES: CONSIDERATIONS 6.3
STORED PROCEDURES: CONSIDERATIONS (Cont..) 6.4
STORED PROCEDURES: CALL SYNTAX 6.5
STORED PROCEDURES : LINKAGE CONVENTIONS 6.6STORED PROCEDURES : LINKAGE CONVENTIONS (Cont..) 6.7
STORED PROCEDURES : DB2 SETUP 6.8
STORED PROCDEURES: DB2 SETUP (Cont.) 6.9
-
7/28/2019 DB2 Applications
8/167
UNIT 7: DB2 UTILITIES
OVERVIEW 7.1
CATEGORIES OF DB2 UTILITIES 7.2
DATA CONSISTENCY UTILITIES 7.3
DATA CONSISTENCY UTILITIES (Cont.) 7.4
BACKUP AND RECOVERY UTILITIES 7.5
DATA ORGANISATION UTILITIES 7.6
CATALOG MANIPULATION UTILITIES 7.7DATA UTILITIESLOAD 7.8
LOADING DATA IN ONE TALBE 7.9
-
7/28/2019 DB2 Applications
9/167
DB2 PROGRAM PREPARATION
SQL STATEMENT FORMATS (DELIMITERS)
HOST VARIABLES
DB2 DATATYPES Vs HOST VARIABLES
COMPLIERDOESNT UNDERSTAND SQL
DB2 PROGRAM PREPARATION DCLGEN COMMAND
DBRM
COMPILATION AND LINK-EDIT
BIND
PACKAGE
COLLECTION
APPLICATION PLAN ISOLATION
EXPLAIN
-
7/28/2019 DB2 Applications
10/167
SQL STATEMENT FORMATS (DELIMITERS)
EXEC SQLUPDATE
WHERE
END-EXEC.
EXEC SQL
UPDATE
WHERE
;
COBOL
PL/1
Notes:
Whatever the language used, SQL statement will always have to be enclosed between delimiters so that they can
be easily spotted and replaced by something the compilers will be able to understand.
Different delimiters are used for different languages. These are the standard delimiters used in COBOL and PL/1.
-
7/28/2019 DB2 Applications
11/167
DB2 DATA TYPES - CHARACTER DATA TYPE
- CHAR(n) / CHARACTER(n)
Fixed length string between 1 and 254 bytes
- VARCHAR(n)
Variable length string
- LONG VARCHAR
Variable length string
-
7/28/2019 DB2 Applications
12/167
-
7/28/2019 DB2 Applications
13/167
NUMERIC DATA TYPE
- SMALLINT
Half word (2 Bytes)
Whole number between + and32K
- INTEGER / INT
Full word (4 bytes)
Whole number between + and2 GB
- NUMERIC(N)
Max 31 digits
- DECIMAL(P,S) / DEC(P,S)
Max 31 digits
- FLOAT(X) / REAL / DOUBLE PRECISION / FLOAT
Full word or double word (4 bytes)
Floating point number between 5.4E-79 and 7.25+75
Notes:
When calculations have to be performed Numeric Data Type have to be used.
-
7/28/2019 DB2 Applications
14/167
DATE / TIME DATA TYPES
DATE 4 Bytes (YYYYMMDD)
TIME 3 Bytes (HHMMSS)
TIMESTAMP 10 Bytes (YYYYMMDDHHMMSSNNNNNN)
Notes:DB2 does the necessary verifications on the data that is entered in these types.
Theycan be manipulated using SQL scalar functions like DAYS, MONTH, YEAR .
-
7/28/2019 DB2 Applications
15/167
NULL ATTRIBUTE
NULL is a special value indicating the absence of a value.
Not consider for the column function evaluations (AVG) except COUNT.
Two nulls are not considered as equal, except for
- GROUP BY
- ORDER BY
Uniqueness of a column unless you use UNIQUE WHERE NOT NULL
Notes:
DB2 considers two null values as equal when it enforces the uniqueness of columns. You can
change this by using the UNIQUE WHERE NOT NULL parameter.
-
7/28/2019 DB2 Applications
16/167
NULL ATTRIBUTE (Cont.)
CHOICE TO BE MADE WHILE DEFINING COLUMNS:
- (Default: NULLS allowed)
- NOT NULL
- WITH DEFAULT
Notes:The NULL attribute of a column is an important choice that will have to be made in cooperation with DBA.
-
7/28/2019 DB2 Applications
17/167
(NOT NULL) WITH DEFAULT
- Same as NOT NULL
- System default values
- ZERO for NUMERIC columns
- BLANKS for fixed length CHARACTER columns
- Blanks for fixed length GRAPHIC columns
- Zero length string for variable length CHARACTER and GRAPHIC columns.
- Current date for DATE data type.
- Current time for TIME data type.
- Current timestamp for TIMESTAMP data type.
-
7/28/2019 DB2 Applications
18/167
-
7/28/2019 DB2 Applications
19/167
HOST VARIABLES
Host language variables that can be referenced in a SQL statement to supply values to DB2 or to
receive values from DB2.
They must be preceded by : when referenced in a SQL statement.
Example
EXEC SQL
SELECT PHONENO INTO :PHONENOFROM EMP
WHERE EMPNO = :EMPNO
END-EXEC.
Notes:
Host variables will be used by DB2 to:
Retrieve data and put it in to host variable for use by application program
INSERT data in to a table or to update it from the data in the host variable.
Evaluate a WHERE or HAVING clause using the data in the host variable.
However, host variable cannot be used to represent a table, view or a column.
The colon( : ) is necessary to distinguish a host variable from a column name.
-
7/28/2019 DB2 Applications
20/167
-
7/28/2019 DB2 Applications
21/167
DB2 DATA TYPES VS HOST VARIABLES
Notes:This table shows how to define a host variable in a program to match a given DB2 data type.
It is important to use the correct data type in our program. Although DB2 will, in many cases,
convert the data type to make the data type match, this could lead to bad performance and should be avoided.
DB2 COBOL PL/1
SMALLINT PIC S9 (4) COMP BIN FIXED (15)
INTEGER PIC S9 (9) COMP BIN FIXED (31)
-
7/28/2019 DB2 Applications
22/167
HOST STRUCTURES
COBOL
01 PHONEEMP.
05 EMPNO PIC X (06).
05 FIRSTNAME.
49 FIRSTNAME-LEN PIC S9 (4) COMP.
49 FIRST NAME-TEXT PIC X (12).
05 MIDINIT PIC X (01).
05 LASTNAME.
49 LASTNAME-LEN PIC S9 (4) COMP.
49 LASTNAME-TEXT PIC X (15).
05 WORKDEPT PIC X (03).
05 PHONENO PIC X (04).
PL/1
DCL 1 PHONEEMP
5 EMPNO CHAR (06),
5 FIRSTNAME CAHR (12) VARYING,
5 MIDINIT CAHR (01),
5 LASTNAME CAHR (15) VARYING,
5 WORKDEPT CHAR (03),
5 PHONENO CHAR (04);
Notes:
A host structure is a group of host variables referred to by a single name in an SQL statement.
They are defined by statements of the host language.
-
7/28/2019 DB2 Applications
23/167
SELECTION OF A SINGLE ROW
Using individual host variables:
EXEC SQLSELECT EMPNO, FIRSTNAME, MIDINIT, LASTNAME,
WORKDEPT, PHONENO
INTO :EMPNO, : FIRSTNAME, :MIDINIT, :LASTNAME,
: WORKDEPT, : PHONENO
FROM EMP
WHERE EMPNO= :INPEMPNO
END-EXEC.
Using the host structure:
EXEC SQL
SELECT * INTO :DCLEMP
FROM EMP
WHERE EMPNO =:INPEMPNO
END-EXEC.
SELECT .INTOFROM. is valid only for Selects that return one row
Notes:
The examples shows how a SELECT statement can be written (to retrieve a single row), both by
referring to individual host variables or by referring to a structure.
-
7/28/2019 DB2 Applications
24/167
COMPILERS DONT UNDERSTAND SQL
Who will get rid of the EXEC SQL so that your program can be compiled?
Answer:
A PRECOMPILER will replace the EXEC SQL statements by CALLS
It will also verify whether
Your SQL statements are correct
Your host variables match the DB2 data types
But it doesnt access DB2
You must include EXEC SQL DECLARE TABLE
Example:
EXEC SQL
DECLARE EMP TABLE
(EMPNO CHAR (6) NOT NULL,
LASTNAME CHAR(10))
END-EXEC.
Notes:
Besides allowing the precompiled to verify the compatibility of host variables versus DB2 column data types
(the precompiled doesnt access DB2, so YOU have to provide the DB2 data type info), it is good practice to
use DECLARE TABLE, because it makes your programs more readable and more easily maintainable.
-
7/28/2019 DB2 Applications
25/167
DB2 PROGRAM PREPARATION STEPS
PRECOMPILER
Bind PackageDBRM
Bind Plan
Source
Program
DCLGEN
Modified
Source
Compiler
Compiled
Source
Linkage-Editor
Load Module
Plan
DB2Catalog
DB2
Directory
Package
DB2 Bind convertsthe DBRM in to an
executable format.
The DB2
Catalog stores
the information
about the plan
and the package.
The DB2
Directory
stored the
actual plan and
the package.
The DB2 Pre-
Compiler produces a
DBRM and a
modified sourceprogram with
commented SQL
statements
-
7/28/2019 DB2 Applications
26/167
PRECOMPILATION
The DB2 application program contains COBOL code with SQL statements embedded in it. The
COBOL compiler will not be able to recognize the SQL statements and will give compilation
errors. So before running the COBOL compiler, the SQL statements must be removed from the
source code. Recompilation does the following:
Searches for and expands DB2 related INCLUDE members.
Searches for SQL statements in the body of the programs source code.
Creates a modified version of the source program in which every SQL statement in
the program is commented and replaces with a CALL to the DB2 runtime interface
module, along with applicable parameters.
Extracts all the SQL statements and places them in a Database Request Module
(DBRM).
Places A Timestamp token in the modified source and the DBRM to ensure that these
two items are inextricably tied.
Reports on the success of failure of the precompiled process.
-
7/28/2019 DB2 Applications
27/167
DCLGEN COMMAND
DCLGEN (Declaration Generator)
Option 2 in DB2
Produces
SQL DECLARE TABLE statement
Host language variable declaration for a table or view
(DECLARE table SQL)
EXEC SQL
DECLARE EMPTABLE
(EMPNO CHAR (6) NOTNULL,
LASTNAME CHAR(15))
END-EXEC.
(Data declaration source code)
01 DCLEMP.
05 EMPNO PIC X (6),
05 LASTNAME PICX(15).
Notes:
The DCLGEN tool provided with DB2I produces a COBOL copybook, which contains SQL DECLARE
TABLE along with the WORKING-STORAGE host variable definitions for each column of the table. Input
will be the language (COBOL, PL/1) and the table name.
DB2 Catalog
DCLGEN
Table
Lang
Include
member
-
7/28/2019 DB2 Applications
28/167
DCLGEN COMMAND (Cont.)
This is the interactive DB2 environment to prepare the program for execution.
DB2 PRIMARY OPTION MENU
1SPUFI
2DCLGEN
3PROGRAM PREPARATION
4PRECOMPILE
5BIND/REBIND/FREE
6RUN
7DB2 COMMANDS
8UTILITIES
D DB2I DEFAULTSX EXIT
Notes:
When DCLGEN command is issued, DB2 read the catalog to fetch the column definition for the table, and
will generate an include member with the DECLARE TABLE and the host structure. DCLGEN command
can be eliminated by hard coding in the application program. But it is a good practice to run the DCLGEN
command for every table that will be embedded in a COBOL program. Then every program that accesses that
table can INCLUDE that generated copybook. This reduces a lot of unnecessary coding. DCLGEN will
generate the host variables with the same name as the column name and if the program uses two tables which
have common column names, then edit the copybook and change the names.
-
7/28/2019 DB2 Applications
29/167
SQL INCLUDE STATEMENT SQLCA
EXEC SQL
statement and
Update the
Communication
Area.
SQL Stmt
SQLCA
DCL 1 SQLCA.
2SQLCAID CHAR (8).
2SQLCABC.
2SQLCODE.2.
2.
2.
2 SQLSTATE CHAR (5).
EXEC SQL
INCLUDE SQLCAEND-EXEC.
Program after compilation
Notes:
SQLCA fields are updated by DB2; the application program must check value. SQCA SQLCODE and
SQLSTATE fields used to check result other field used for more detailed on condition. In order to know what
happened in the other side in DB2 we must provide DB2 with program storage where it can set a return code andother information DB2 wants to communicate
-
7/28/2019 DB2 Applications
30/167
DBRM
Data Base Request Module contains the programs source SQL statements.
A DBRM
Contains the extracted, parsed SQL source.
Is stored as a member in a partitioned dataset. One member created per precompile.
Will become Input to BIND.
-
7/28/2019 DB2 Applications
31/167
DBRM (Cont.)
One DBRM corresponds to exactly one source module. The SQL statements in the source program
will be replaced by CALL to module DSNHLI statement with the following parameters.
DBRM name (SQLPROGN)
Timestamp (SQLTIME)
Statement number (SQLSTNUM)
Other parameters are
Address of host variables.
Address of SQLCA.
At this stage, the two components, (DBRM and modified source), will part and wont see each
other again until program execution. Therefore the CALL must include necessary information for
DB2 to be able to locate the access path needed to execute the SQL statement associated with the
CALL.
The information about the DBRM that have been bound in to the application plans and packages is
stored in the SYSIBM.SYSDBRM in the DB2 catalog table. If a DBRM is created and is not
bound cannot be referenced from this table.
When DBRM is bound to a plan, all the SQL statements are placed in to thSYSIBM.SYSTMTDB2
catalog table. When a DBRM is bound in to a package all the SQL statements are placed in to the
SYSIBM.SYSPACKSTMT table.
-
7/28/2019 DB2 Applications
32/167
COMPILATION AND LINK-EDIT
After pre-compilation the program has to be COMPILED and LINK-EDITED. This can be
done using:
DB2I panels. JCL.
PL/1 PRECOMPILER can precede the DB2 PRECOMPILER.
CICS COMMAND TRANSTLATOR may have to be invoked.
Object Module
DSNELI
DSNELI
Load Module
COMPILE
DSNHLI
LINK-EDIT
-
7/28/2019 DB2 Applications
33/167
Notes:
The modified program is now ready to be compiled and link-edited. The link-edit will have to include the
necessary modules for the call to work properly. The appropriate LANGUAGE INTERFACE must be included.The program that has been prepared here will run in one of the many execution environments like TSO, CICS,
IMS. Depending on the environment, a different interface module will have to be included in the link-edit stop.
The name of the module will vary, but they will all have an entry point DSNHLI.
-
7/28/2019 DB2 Applications
34/167
BIND PACKAGE
BIND PACKAGEDBRM
Validates SQL
Resolves Table Names
Checks Privileges
Chooses an access path based on
catalog statistics
Stores source SQL in catalog
Stores executable access path
(PACKAGE) in Directory
PACKAGE
CREATE
TABLE
GRANT
TO
RUNSTATS
UTILITY
OBJECT
DEFINITION
SSECURITY
DEFINITION
STATISTICS
SQL
STATEMENTS
DB2
Catalog
Collection
DB2
Directory
-
7/28/2019 DB2 Applications
35/167
BIND PACKAGE (Cont.)
Validating: Checking whether the table exist.
Resolving usernames: Completing table names with their owners incase they were
omitted.
Authority checking is performed to make sure that the BIND has the authority to create a
program to access the data as required.
Access path selection consists of evaluating a number of different access paths and
calculating their costs. The cheapest one will be retained. Those cost estimates are based on
statistics, which are stored in the catalog. The RUNSTATS utility must be run to keep those
statistics up-to-date.
The executable access code is stored in the directory, and the source SQL statements are
stored in the DB2 catalog. They may be needed if the access path were to be evaluated at
some later time.
-
7/28/2019 DB2 Applications
36/167
PACKAGE
DBRM
BIND PACKAGE (collx)
MEMBER (dbrma)
BIND PACKAGE (colly)
MEMBER (dbrma)
dbrma dbrma
Package Name = Collection_id.Package_id
-
7/28/2019 DB2 Applications
37/167
PACKAGE (Cont.)
A package is a single bound DBRM with optimized access path. By using packages the table
access logic is packaged at a lower level for granularity at the package or program level.
To execute a package it must be first be included in the package list of a plan. Package can
never be directly executed; they are only executed when the plan in which they are
contained is executed.
A plan can consist of one or more DBRMs, one or more packages, or a combination of
packages and DBRMs.
Package information is stored in its own DB2 catalog tables. When a package is bound, DB2
reads the following catalog tables:
SYSIBM.SYSCOLDIST, SYSIBM.SYSCOLUMNS, SYSIBM.SYSFIELDS,
SYSIBM.SYSINDEXES,SYSIBM.SYSPACKAGES,SYSIBM.SYSTABLES
SYSIBM.SYSPACKAUTH,SYSIBM.SYSTABLESPACE and SYSIBM.SYSUSERAUTH
Of the above tables SYSIBM.SYSUSERAUTH table is read only for BIND ADD.
The DB2 catalog stores information only about the packages. The executable form of the package
is stored as a skeleton package table in the DB2 directory in the SYSIBM.SPTOI1 table. A package
also contains a location identifier, a collection identifier and a package identifier. These are
identifiers used to uniquely identify the packages.
-
7/28/2019 DB2 Applications
38/167
COLLECTIONS
A collection is a set of Packages.
Test Prod
A collection is IMPLICITLY created a first BIND PACKAGE referring to that collection.
BIND PACKAGE (test) MEMBER (pkg1)
BIND PACKAGE (test) MEMBER (pkg2)
pkg2
pkg1 pkg2
pkg1
-
7/28/2019 DB2 Applications
39/167
Notes:
A collection is a user-defined name (1 to 18 characters) that the programmer must specify for every package.
A collection is not an actual, physical database object. A collection is a grouping of DB2 packages.
By specifying different collection identifier, for a package, the same DBRM can be bound to different
packages. This capability permits the programmer to use the same DBRM for different packages, enabling
easy access to tables that have the same structure, but different owners.
-
7/28/2019 DB2 Applications
40/167
APPLICATION PLAN
A plan is an executable module containing the access path, logic provided by the DB2
optimiser. It can be composed of one or more DBRMs and packages.
Plans are created by the BIND command. When a plan is bound, DB2 reads the following
catalog tables:
SYSIBM.SYSCOLDIST,SYSIBM.SYSCOLUMNS,SYSIBM.SYSFIELDS,
SYSIBM.SYSINDEXES,SYSIBM.SYSPLANS,SYSIBM.SYSPLANAUTH,
SYSIBM.SYSTABLES, SYSIBM.SYSTABLESPACE and SYSIBM.SYSUSERAUTH
The SYSIBM.SYSUSERAUTH table is read only for BIND ADD.
-
7/28/2019 DB2 Applications
41/167
CONSISTENCY TOKENPROGRAM PREPARATION
Pgm3 Pgm1 Pgm2
Dbrm2Dbrm3Dbrm1Mprog1Mprog3Mprog2
PRECOMPILE
Compile / Link BIND PACKAGE
Loadmodule
DB2
Directory
-
7/28/2019 DB2 Applications
42/167
Notes:
The precompilation TIMESTAMP is included in each generated CALL in the modified source.The other twin brother (the DBRM) also contains this timestamp. It will be used by DB2 at program execution
time to locate the correct package for the correct load module.
-
7/28/2019 DB2 Applications
43/167
LOCATING PACKAGES AT EXECUTION TIME
CALL DNHLI (dbrm1, , 1)
.
.
CALL DSNHLI (dbrm1, , 2)
.
..
.
CALL DSNHLI (dbrm2, ,1)
.
.
call
call
call Dbrm1 Dbrm3
Dbrm2
Dbrm1
collx colly
collz
DB2 Directory
-
7/28/2019 DB2 Applications
44/167
THE MISSING LINK
CALL DSNHLI
(dbrm2,
.
CALL DSNHLI
(dbrm1, ,1)
Notes:
In between the load module and the packages there is a need for an additional structure that will guide DB2 in
its searches for the appropriate package. This structure is called a plan and it will contain a package list, a list of
logical pointers to packages. DB2 will look for the right (same timestamp) package by using each entry in the
package list in turn until it has a hit. The mechanism is very similar to the search mechanism by the operating
system to locate a member of a PDS on a concatenation of PDSs. Running a DB2 program is done byassociating the plan with the load module. This is done outside the program.
-
7/28/2019 DB2 Applications
45/167
PLAN AND PACKAGES
A PACKAGE can be located and executed only via a PLAN
A PLAN contains a PACKAGE list a list of pointers to packages.
The DBRM name and the TIMESTAMP provided with the CALL are used to locate
the correct package via the package list.
Notes:
The package list determines which package will be used.
-
7/28/2019 DB2 Applications
46/167
BIND PLANPACKAGE LIST
Notes:
A PACKAGE LIST is a list of references to individual packages (E.G. COLLX.DBRM1) or to sets of packages
(e.g. COLLY. *). A package list makes specific parts of the directory eligible for the package search.
RUN PROGRAM
(Imoda)
PLAN (plana)
CALL DSNHLI (dbrm1, ,2)
CALL DSNHLI (dbrm1, ,1)CALL DSNHLI (dbrm1, ,2)
Dbrm1 Dbrm3
Dbrm2
Dbrm1
Dbrm4
Collx.dbrm1, collz. *
BIND PLAN (plana)
PKLIST (collx.dbrm1, collz. *)collz
collx colly
-
7/28/2019 DB2 Applications
47/167
Collx.dbrm1, collz. *
Collx.dbrm1, collz. *
Dbrma Dbrm1
Dbrm1 Dbrm2
plana
plana
plana
BIND PLAN (plana)
PLSIST (collx.dbrm1, collz. *)
BIND PLAN (plana)
PKLIST (collx.dbrm1, collz. *)
MEMBER (dbrma, dbrm1)
BIND PLAN (plana)
MEMBER (dbrm1, dbrm2)
BIND PLAN DBRMs
Notes:
Packages were introduced with DB2 V2.3, but plans already existed. Previously, the DBRMs were bound directly
into the plan structure itself. For compatibility reasons, DB2 also supports this today.
-
7/28/2019 DB2 Applications
48/167
UNIT 2: DB2 INTERNALS : OVERVIEW
OVERVIEW
DATA STORAGE
THE OPTIMIZER
DB2 CATALOG & DIRECTORY
DATA LOCKING
-
7/28/2019 DB2 Applications
49/167
DATA STORAGE
There are two types of DATA STORAGE.
Logical storage
Physical storage
Notes:
Logical storage is how the user sees the data. Physical storage is how data is actually stored. The total collection
of stored data is divided into a number of user databases and system databases. Each database is divided into
number of table spaces and index spaces.
A space is a dynamically extendible collection of pages, where a page is a block of physical storage. The pages ina given space are all of the same size 4KB for index spaces and either 4KB or 32KB for table spaces. Each table
space contains one or more tables. A stored table is a physical representation of a base table; it consists of a set of
stored records, one for each row of the base table.
A given stored table must be wholly contained with in a single table space. Each index space contains exactly one
index. A given index must be wholly contained in an index space. A given stored table and all its associated
indexes must be wholly contained with in a single database.
-
7/28/2019 DB2 Applications
50/167
DATA STORAGE (Cont.)
Stored
Table
Stored
Table
Stored
TableCatalog
Table
Stored
Table
Catalog
Table
Catalog
TableStored Table Stored Table
Stored Table
Index
IndexIndex
View View View
T
A
B
LE
SP
A
C
E
IN
D
E
X
SP
A
C
E
User
Database
User
Database
Catalog
Database
Storage Group 1 Storage Group 1
-
7/28/2019 DB2 Applications
51/167
DATA STORAGE (Cont.)
DATABASES:
A database is a collection of logically related objects. That is a collection of stored tables that are
related together in some way, together with their associated indexes and the various spaces that
contain those tables and indexes. It thus consists of a set of table spaces and index spaces.
TABLESPACES:
A table space can be considered a logical address space on secondary storage that is used to hold oneor more stored tables. As the amount of data in those tables grows, storage will be acquired from the
appropriate storage group and added to the table space. One table space can be up to approximately
64 billion bytes in size. The table space is the storage unit for recovery and reorganization purposes,
i.e., it is the unit that can be recovered via RECOVER utility or reorganized using the REORG
utility. If the table space is very large, then recovery and reorganization can take a very long time.
Table spaces can be of three types
1. Simple
2. Partitioned
3. Segmented
-
7/28/2019 DB2 Applications
52/167
A simple table space can contain more than one stored table, though one is the best
option. One reason for having more than one table is that related data can be kept
together, making the access faster. Partitioned table spaces are intended for tables that
are sufficiently large i.e. operationally difficult to deal with the entire table as a single
unit.
A partitioned table space thus contains exactly one table, partitioned in accordance with
the value ranges of a partitioning column or column combination.
In the segmented table spaces, the space with in the table space is divided in to
segments, where each segment contains logically contiguous n pages where n must
be a multiple of 4 and must range between 4 and 64 and should be the same in allsegments. No segment will have records of more than one stored table and if the table
grows in size to fill a segment a new segment will be obtained
-
7/28/2019 DB2 Applications
53/167
DATA STORAGE (Cont.)
INDEXSPACES:
An index space is to an index like a table space is to a table. The correspondence between indexes
and index spaces are always one-to-one, there are no data definition statements to index spaces.
Thus there is no CREATE INDEX SPACE but only CREATE INDEX, which will automatically
create the index space. Index spaces are always 4 KB in size.
INDEXES:
Indexes in DB2 are based on a structure known as B-Tree. B-Tree is a multilevel, tree structure
index with a property that tree is always balanced, which means that all the leaf entries in the
structure are equidistant from the root of the tree and this property is maintained as new entries are
inserted into or existing entries are deleted from the tree.
STORAGE GROUPS:
Storage groups are named collections of direct access volumes, all of the same device type. Each
table space each index space normally has an associated storage group. When storage is needed for
the space or partition, it is taken from the specified storage group. Within each storage group,
spaces and partitions are stored using VSAM linear datasets. DB2 uses VSAM for such things as
direct access space management, dataset cataloging, and physical transfer of pages into and out of
memory.
-
7/28/2019 DB2 Applications
54/167
NORMALIZATION 1-NF
Normalization is the process of steps that will identify for elimination of redundancies in a
database design.
FIRST NORMAL FORM: Eliminating repeating groups
Unnormalized EMPL
EMPNO LASTNME WORKDEPT DEPTNAME SKILL1 SKILL2 SKILLN
000030 KWAN GRE OPERATIONS 141
000250 SMITH BLU PLANNING 002 011 067
000270 PEREZ RED MARKETING 415 447
000300 SMITH BLU PLANNING 011 032
Notes:Eliminating Repeating Groups:
One of the first rules of relational tables is that all the rows must have the same number of columns and each
column must mean the same thing in the same sequence in each row.
In the example of EMP table, if it were required to represent the multiple skills of employees, this would be
represented in an additional table where each skill for a given employee is represented in a row. If new skill is
created and an employee already has the maximum number of skills allocated in the data structure, then the entire
file structure and all the programs have to be changed, in an unnormalized file structure. If this table is normalized,then the new skill simply becomes a new row.
-
7/28/2019 DB2 Applications
55/167
NORMALIZATION 1-NF (Cont.)
NORMALIZED TO 1NF-EMPL
EMPL_SKILL TABLE
EMPNO LASTNAME WORKDEPT DEPTNAME
000030 KWAN GRE OPERATIONS
000250 SMITH BLU PLANNING
000270 PEREZ RED MARKETING
000300 SMITH BLU PLANNING
EMPNO SKILLSKILLDESC
000030141RESEARCH
000250002BID PREP
000250011NEGOTIATION
000250067PROD SPEC000270415BENEFITS ANL
000270447TESTING
000300011NEGOTIATION
000300032INV CONTROL
-
7/28/2019 DB2 Applications
56/167
NORMALIZATION 2-NF
Second normal form Eliminate the columns that depend only on part of the key
EMPNO SKILL SKILLDESC
000030 141 RESEARCH
000250 002 BID PREP
000250 011 NEGOTIATION
000250 067 PROD SPEC000270 415 BRNRFITS ANL
000270 447 TESTING
000300 001 NEGOTIATION
000300 032 INV CONTROL
Notes:
Second normal form requires a close look at proposed tables that have multi-column primary keys. The
objective is to eliminate all columns from a table design that are dependent on only part of the primary
key
-
7/28/2019 DB2 Applications
57/167
NORMALIZATION 2-NF (Cont
Normalized - 2NF
EMPNO SKILL DATE CERT000030 141
000250 002
000250 011
000250 067
000270 415
000270 447
000300 011
000300 032
SKILLSKILLDESC
002BID PREP
011NEGOTIATION
032INV CONTROL
067PROD SPEC
141RESEACH
415BENEFITS ANL447TESTING
Notes:
In the example of EMP table in the 1NF the skills of the employees was matched with the employees
in a separate table and the skill description. But skill description depends only upon the skill number. The
problems that arise due to this are:
1. The skill description will be repeated every time the skill is repeated.
2. If this description for the skill changes, then multiple rows will need to be changed, risking some
update anomalies (data inconsistency due to not changing all rows).
3. If an employee is the sole source for a given skill and that person leaves the company, that
particularskill and skill description is lost forever. (Delete anomaly).
-
7/28/2019 DB2 Applications
58/167
-
7/28/2019 DB2 Applications
59/167
-
7/28/2019 DB2 Applications
60/167
NORMALIZATION 5-NF
Fifth normalization: Isolate related multiple relationships
Notes:
Suppose in the above example the skills and languages are related to each other, there may be some other
reason why they should be separated in to yet another table to resolve many-to-many relationship between
them. So we should have three tables
1. Employee-Skill
2. Employee-Language
3. Skill-Language
-
7/28/2019 DB2 Applications
61/167
NORMALIZATION RECOMMENDATION
Always Normalize to Third Normal Form.
Analyze the tables Views To Evaluate The Benefits of the denormalizing.
Notes:
Normalization solves many problems like it eliminates redundancies that saves disk space and reduces update
and delete anomalies.
It helps in keeping data model flexible, which is a key factor in todays world of rapidly changing business
requirements, but it may impact performance depending on user requirements if the datas are separated into
many tables, but it is often retrieved, many I/O operations are required than if it is not normalized. These
decisions and trade offs between normalizing and denormalizing has to be decided.
-
7/28/2019 DB2 Applications
62/167
OPTIMIZER
DB2 Optimizer
Query Cost
Formulas
SQL
DB2Catalog
Optimized
Access
Path
Notes:The Optimizer is the most important part of DB2. It is the brain of DB2. It analyzes the SQL
statements and determines the most efficient access path available for satisfying the statement.
In the SQL statements, we only say what we want, the optimizer decides how to get the things that we
have asked for. It accomplishes this by parsing the SQL statements to determine which table must be
accessed.
It then queries statistics stored in DB2 catalog to determine the best method of accomplishing the tasksnecessary to satisfy the SQL statements.
-
7/28/2019 DB2 Applications
63/167
DB2 CATALOG AND DIRECTORY
-
7/28/2019 DB2 Applications
64/167
DB2 CATALOG AND DIRECTORY
DB2 has a set of tables that function as a repository for all DB2 objects, the DB2
Catalog and DB2 Directory. The entire DBMS relies on the DB2 Catalog.
The DB2 Catalog is composed of eleven table spaces and 43 tables all in a single
database DSNDB06.
Each DB2 Catalog table maintains data about an aspect of DB2 environment. In
the respect, DB2 catalog functions as a data dictionary for DB2, supporting and
maintaining data about the DB2 environment.
The DB2 catalog records all information required by DB2 about STOGROUPS,
data spaces, table spaces, partitions, tables, columns, views, synonyms, aliases,
indexes, index keys, foreign keys, relationships, plans, packages, DBRM s,
database privileges, plan privileges, system privileges, table privileges, viewprivileges, use privileges, image copy datasets, REORG executions.
The DB2 catalog is built, maintained and used as a result of the creation of objects
defined to the catalog. In other words as the user creates or modifies the DB2 objects,
metadata (data about data) is being accumulated in the catalog. The DB2 catalog can be
updated using the RUNSTATS utility.
-
7/28/2019 DB2 Applications
65/167
-
7/28/2019 DB2 Applications
66/167
CATALOG STRUCTURE (Cont.)
SYSAUTHSYSPACKAGE
SYSPKSYSTEM SYSPACKLIST SYSPACKDEP
SYSPLAN
SYSPACKLIST
SYSPLSYSTEM
SYSPLANDEPSYSPLANAUTH
SYSDBRM
SYSSTMT
DB2 Catalog: Plans & Packages
-
7/28/2019 DB2 Applications
67/167
CATALOG STRUCTURE (Cont.)
SYSVTREE
SYSVIEWSSYSVLTREE
SYSSTOGROUP
SYSVOLUMES
SYSVIEWDEP
SYSDATABASE
SYSDBAUTH
SYSRESAUTHSYSUSERAUTHSYSSTRINGSSYSCOPY
DB2 Catalog: Views, Stogroups and Database
DB2 DIRECTORY
-
7/28/2019 DB2 Applications
68/167
DB2 DIRECTORY
DB2 uses a second data directory, other than the catalog, called the DB2 Directory for
storing detailed technical information about the aspects of DB2 s operation.
The DB2 directory is for DB2 s internal use only. The SQL statements cannot access thedata in the DB2 directory.
Utilities
SYSUTIL
SYSUTILX
DBD01
SYSLGRNG
SPT01
SCT02
BIND
Active Logs
Archive Logs
DB2
Catalog
DB2 Directory
Application Database
-
7/28/2019 DB2 Applications
69/167
DATA LOCKING
DB2 guarantees data integrity by using several locking mechanisms.
Why data locking?
When multiple users can access and update the same data at the time, a locking
mechanism is required. This mechanism must be capable of differentiating between
stable data and uncertain data. Stable data has been successfully committed and is not
involved in an update in a current unit of work. Uncertain data is currently involved in
an operation and could get modified. If two users try to update the same record at the
same time, or if one user deletes a record while some other user is trying to update it,
with out proper locking strategy and locking mechanisms, the data integrity can go
haywire. To avoid such situations a DBMS uses a locking mechanism.
-
7/28/2019 DB2 Applications
70/167
-
7/28/2019 DB2 Applications
71/167
-
7/28/2019 DB2 Applications
72/167
LOCKS VS LATCHES
A true lock is handled by DB2 using IRLM (IMS Resource Lock Manager). DB2 will try to lock
pages without going to IRLM, whenever it is possible. This type of lock is referred to as a latch.
True locks are always set in the IRLM. Latches, by contrast are set internally by DB2 with out
going to the IRLM. When a latch is taken instead of lock, it is handled by internal DB2 code. So
cross memory service calls to IRLM is eliminated. Also a latch requires about one third of
instruction as a lock. Therefore, latches are more efficient than locks because they avoid theoverhead associated with calling an external address space.
Latches are used when a resource serialization is required for a short time. Prior to DB2 version 3,
latches were generally used to lock only DB2 index spaces and internal DB2 resources. When
running V3, DB2 uses latching more frequently. This includes data page latches.
DEADLOCKS AND TIMEOUTS
-
7/28/2019 DB2 Applications
73/167
Locks can be used to solved problems of concurrency, and ensure data integrity. But
unfortunately, locking introduces a problem called deadlock.
Deadlock is a situation in which two or more transactions are in simultaneous wait state,
each waiting for one of the others to release a lock before it can proceed.
If a deadlock occurs the system will detect and break it. Breaking a deadlock involves
choosing one of the deadlock transactions as the victim and depending on the transaction
manager concerned, either rolling it back automatically or requesting it to roll back itself.
Either way, the transaction will release its locks and thus allow some other transactions to
proceed.
In general, therefore, any operation that requests a lock may be rejected with a negative
SQL code indicating the transaction has been selected as the victim of a deadlock situation
and has either been rolled back or request to roll back.
A time-out is caused by the unavailability of a given resource. Time outs are caused when a
transaction has to wait for a resource, which is held by another transaction. The duration of
the waiting time, after which the time-out should occur is determined by the IRLMRWT
DSNZPARM parameter
-
7/28/2019 DB2 Applications
74/167
UNIT 3. CURSOR HANDLING
OVERVIEW
DEFINING CURSORS
CURSOR DECLARATION
UPDATING/DELETING WITH CURSORS
READ ONLY CURSORS
-
7/28/2019 DB2 Applications
75/167
DEFINING CURSORS
Two types of embedded SQL SELECT STATEMENTS.
Singleton SELECT
Cursor SELECT
SQL statements operate on a set of data and return a set of data. Host language programs,
on the other hand, operate on a row at a time.
A singleton SELECT is simply on SQL SELECT statement that returns a single row. The singleton
SELECT differs from the ordinary SELECT statement in that it contains an INTO clause. The
INTO clause is where you code your host variables that accept the data returned by DB2. But if
such a SELECT statement returns more than one row, the values of the first row is placed in the
host variable and DB2 issues an SQLCODE of811. So, in your application program, if the
SELECT will return more than one row then one must use Cursors.
DB2 uses cursors to navigate through a set of rows returned by an embedded SQL SELECT
statement. A cursor can be compared to a pointer. The programmer declares a cursor and defines the
SQL statement for the cursor. After that you can use the cursor like a sequential file. The cursor is
opened, rows are fetched from the cursor, and one row at a time and at the end of processing the
cursor is closed.
-
7/28/2019 DB2 Applications
76/167
DEFINING CURSORS (Cont...)
The four operations that must be performed for the successful working of cursors.
DECLARE - This statement defines the cursors, gives a name to it and assigns an SQL
statement to it. The DECLARE statement does not execute the SQL statement but merely defines it.
OPENThis readies the cursor for row retrieval. OPEN is an executable statement. It reads theSQL search fields, executes the SQL statements and sometimes builds the result table.
FETCH - This statement returns data from the result table one row at a time to the host variables.
If the result table is not built at the OPEN time, it is built during FETCH.
CLOSEReleases all resources used by the cursor.
SAMPLE PROGRAM FOR CURSOR
-
7/28/2019 DB2 Applications
77/167
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE dclgenmem
END-EXEC.
EXEC SQLINCLUDE SQLCA
END-EXEC.
PROCEDURE DIVISION.
EXEC SQL
DECLARE CUR CURSOR FOR SELECT * FROM S
END-EXEC.
EXEC SQLOPEN CUR
END-EXEC.
PERFORM FETCH-PARA UNTIL SQLCODE = 100.
FETCH-PARA.
EXEC SQL
FETCH CUR INTO :DCLS
END-EXEC.IF SQLCODE = 100
EXEC SQL
CLOSE CUR
END-EXEC
STOP RUN
END-IF.
DISPLAY DCLS.
CURSOR DECLARATION
-
7/28/2019 DB2 Applications
78/167
EXEC SQL DECLARE CURSOR-NAME
CURSOR (WITH HOLD) FOR select-statement
- A Cursor : Is required for select of multiple rows
Is never used for INSERT
May be reused (CLOSE + new OPEN)
Will be closed at COMMIT
Unless declared with WITHHOLD
- Multiple Cursors :
May be defined in a program
May work with the same table
May be open simultaneously
Notes:
The DECLARE CURSOR statement is used to associate a cursor with the SQL statement. No data access is
performed at this stage.
The WITH HOLD option is important if you want to issue COMMIT inside the fetch loop. If you omit this
keyword, you will have to re-open (and DB2 will have to re-execute the access path) the cursor after each
COMMIT, because its position will be lost due to the COMMIT.
UPDATING /DELETING WITH THE CURSORS
-
7/28/2019 DB2 Applications
79/167
Row-at a time UPDATE OR DELETE (Positioned Updates)
- Declare
FOR UPDATE OF.option
EXEC SQL DECLARE CUR1 CURSOR FOR
SELECT EMPNO, LASTNAME
FROM EMP
WHERE WORKDEPT =: DPT
FOR UPDATE OF LASTNAME
- and use
WHERE CURRENT OFoption
EXEC SQL OPEN CUR1
EXEC SQL FETCH CUR1 INTO: EMPNO, NAME
IF
EXEC SQL UPDATE EMP
SET LASTNAME =: NEWNAME
WHERE CURRENT OF CUR1.
EXEC SQL FETCH CUR1 INTO: EMPNO, NAMEIF THEN
EXEC SQL DELETE FROM EMP
WHERE CURRENT OF CUR1.
Notes:
Once the cursor is positioned on a row, you can do a Positioned update or delete. It means that the update/delete
doesn't require that DB2 re-access the data and it would have to do if you used delete where key =.
-
7/28/2019 DB2 Applications
80/167
-
7/28/2019 DB2 Applications
81/167
READ-ONLY CURSORS (Cont...)
A Read-only cursor cannot be thetarget of a positioned update/delete
However, some cursors are read/only. The reason behind this is that for some SQL statements,
it will not be possible for DB2 to position itself before the first result row without accessing theentire result set. Take the example of a SELECT..ORDER BY. DB2 will have to get all
qualifying rows and sort them before it can position its cursor. In addition, the cursor will be
positioned on an intermediate result table and not on the actual data itself.
-
7/28/2019 DB2 Applications
82/167
UNIT 4. DYNAMIC AND STATIC SQL
OVERVIEW
STATIC SQL
DYNAMIC SQL
-
7/28/2019 DB2 Applications
83/167
STATIC SQL
STATIC SQL
Can be used if the statements
TYPE
TABLES
COLUMNS, WHERE- Clause are known when you write your program
The complete SQL statement is contained in the program, except
for host variable referring to COLUMN VALUES. BIND creates the access path
Only the EXECUTE privilege is checked before execution
of the access path
Program
Get host variable
contents
EMPN
-
7/28/2019 DB2 Applications
84/167
-
7/28/2019 DB2 Applications
85/167
DYNAMIC SQL (Cont)
NON-SELECT DYNAMIC SQL
EXECUTE IMMEDIATE
PREPARE FOR EXECUTE IMMEDIATE
SELECT DYNAMIC SQL
FIXED-LIST SELECT
.VARYING-LIST SELECT
EXECUTE IMMEDIATE
-
7/28/2019 DB2 Applications
86/167
EXECUTE IMMEDIATE implicitly prepares and executes complete SQL statements coded in
host variables. Only a sub-set of SQL statements is available when you use this command, the
prominent being SELECT and so this call of dynamic SQL cannot be used for data retrieval. Soif you want any data to be retrieved then the SQL portion of your program consists of two steps.
First moving the complete text for the statement to be executed to be executed into the host
variable and second issue an EXECUTE IMMEDIATE command giving the host variable as an
argument. The statement is prepared and execute automatically.
Ex:
WORKING-STORAGE SECTION. :
EXEC SQL
INCLUDE SQLCA
END-EXEC.
01 WS-HOST-VARIBLE.
49 WS-HOST-VARBLE-LEN PIC S9 (4) COMP.49 WS-HOST-VARBLE-TXT PIC X(80).
PROCEDURE DIVISION.
MOVE +45 TO WS-HOST-VARBLE-LEN.
MOVE DELETE FROM EMPLOYEE WHERE DEPT=CONSUL
TO WS-HOST-VARBLE-TXT.
EXEC SQL
EXECUTE IMMEDIATE :WS-HOST-VARBLE
END-EXEC.
-
7/28/2019 DB2 Applications
87/167
EXECUTE IMMEDIATE (Cont)
The Execute Immediate supports following statements
ALTER, CREATE, DELETE, DROP, EXPLAIN, COMMIT, GRANT, INSERT,
REVOKE and UPDATE.
Disadvantages of EXECUTE IMMEDIATE
It does not support the SELECT statement.
It can result in poor performance, if the same SQL statement is performed, the executable
form of the SQL is destroyed and the program has to prepare the executable form when it
executed again.
NON-SELECT DYANMIC SQL
-
7/28/2019 DB2 Applications
88/167
This statement is used to prepare and execute the SQL statements in an application program. This
class of SQL statements uses PREPARE and EXECUTE to issue the SQL statements. As the name
suggests this class also does not support the SELECT statements and cannot be used for querying
tables.Non-SELECT SQL statements can use the feature of dynamic SQL known as the parameter
marker (?), which is a placeholder for the host variables in the SQL.
WORKING-STORAGE SECTION.
01 TVAL PIC X(10)
01 WS-HOST-VAR.
49 WS-HOST-VAR-LEN PIC S9 (4) COMP.
49 WS-HOST-VAR-TXT PIC X(100).
EXEC SQL
INCLUDE SQLCA
END-EXEC.
PROCEDURE DIVISION.
MOVE +45 TO WS-HOST-VARBLE-LEN.
MOVE DELETE FROM S WHERE S#= ? TO WS-HOST-VAR-TXT.
EXEC SQL
PREPARE STMT1 FROM :WS-HOST-VARBLE
END-EXEC.
MOVE CONSUL TO TVAL.
EXEC SQL
EXECUTE STMT1 USING :TVAL
END-EXEC.
FIXED-LIST SELECT
-
7/28/2019 DB2 Applications
89/167
A FIXED-LIST SELECT statement can be used to explicitly prepare and execute SQL SELECT
statements when the column to be selected are known and unchanging. This is necessary to create
the WORKING-STROAGE declaration for the host variable in the program.
Example
WORKING-STORAGE SECTION.
01 WS-HOST-VAR.
49 WS-HOST-VAR-LEN PIC S9 (4) COMP.
49 WS-HOST-VAR-TXT PIC X(100).
01 TVAL1.
49 TVAL1-LEN PIC S9 (4) COMP.
49 TVAL1-TXT PIC X(3).
01 TVAL2 PIC X (10 ).
PROCEDUER DIVISION.
MOVE SELECT S#, SNAME, STATUS, CITY FROM S
WHERE S# = ? AND CITY= ?
TO FLSQL.
Move the SQL to execute to WS-HOST-VARBLE.
EXEC SQL
DECLARE CRS1 CURSOR FOR FLSQL
END-EXEC.
FIXED LIST SELECT (Cont )
-
7/28/2019 DB2 Applications
90/167
FIXED-LIST SELECT (Cont)
EXEC SQL
PREPARE FLSQL FROM :WS-HOST-VAREND-EXEC.
Move the required values to the variables TVAL1 and TVAL2.
EXEC SQL
OPEN CRS1 USING :TVAL1, :TVAL2END-EXEC.
Loop until no more rows to fetch
EXEC SQL
FETCH CRS1 INTO :S#,:SNAME, :STATUS, :CITYEND-EXEC.
EXEC SQL
CLOSE CRS1
END-EXEC.
-
7/28/2019 DB2 Applications
91/167
-
7/28/2019 DB2 Applications
92/167
SELECT STATEMENT WITH VARYING LIST (C t )
-
7/28/2019 DB2 Applications
93/167
SELECT STATEMENT WITH VARYING LIST (Cont...)
Since we dont know which columns will be accessed, we cannot pre-allocate any storage for hostvariables until we know that information. This will be the thing to do.
If we have an idea how many columns we will have to access, it will already simplify our case.
In Order to now the data types and names of the columns, we will have to ask DB2 to
DESCRIBE the table we access. DB2 needs storage to be able to do this describe. If you know
how many columns you will need, you can at least allocate enough storage for DB2 to be able to
do the DESCRIBE. Once this is done, you can allocate storage for the host variables and execute
the statements.
SQL DESCRIPTOR AREA (SQLDA) - FUNCTION
-
7/28/2019 DB2 Applications
94/167
SQL DESCRIPTOR AREA (SQLDA) FUNCTION
Column Name,
Data Type And
Length For
Each Column
Selected
Addresses of host
variables to receive
results
Allocate matching
host variables to
receive a single
row
Place addresses of
host variables intoSQLDA
SQLDADESCRIBE INTO SQLDA
FETCH USING SQLDA
Notes:
This is the host structure used by DB2 describe an SQL statement (number of columns and data
type of each column). This will be the input for the allocation of the host variable storage.
SQLDA FORMAT
-
7/28/2019 DB2 Applications
95/167
SQLDA - FORMAT
SQLDAID CHAR(8) SQLD ABC INTEGER
SQLN SMALLINT SQLD SMALLINT
SQLTYPE SMALLINT SQLLEN SMALLINT
SQLDATA POINTER SQLIND POINTER
SQLNAME VARCHAR
(30)
OTHER SQLVARS
One
Structure
For Each
Column
Selected(SQLVAR)
Notes:
The SQLDA has a header containing some very useful information ( number of columns,
etc), and then for each column a descriptive are called SALVAR.
SQLDA COLUMN DESCRIPTION
-
7/28/2019 DB2 Applications
96/167
SQLDA COLUMN DESCRIPTION
SQLTYPE DATA TYPE LENGTH
384 DATE, NOT NULL Inst. Dep
388 TIME, NOT NULL Inst. Dep
392 TIMESTAMP, NOT NULL 26
448 VARCHAR, NOT NULL Length
452 CHAR, NOT NULL Length
480 FLOAT, NOT NULL 8480 REAL, NOT NULL 4
484 DECIMAL, NOT NULL 2(prec/scale)
496 INTEGER, NOT NULL 4
500 SMALLINT, NOT NULL 2
SQLTYPE + 1 = same as SQLTYPE, WITH nulls allowed
Notes:
The SQLDA column description uses SQL TYPES to identify the different DB2 data types for
columns. The Null attribute is also implicitly included.
SQLDATechnique 1
-
7/28/2019 DB2 Applications
97/167
Allocate SQLDA1 for pre-defined number of columns (e.g. sqln = 50)
SQLDAID SQLDABC SQLN SQLD
SQLTYPE SQLTYPE SQLDATA SQLIND SQLNAME
:
:
:
SQLN
#50
DESCRIBE statement INTO SQLDA1
If less than 50 columns returned Allocate host variable and indicator variable storage
OPEN CURSOR and FETCH
If more than 50 columns returned
Read SQLD (# cols)
Reallocate SQLDA2
Describe statement INTO SQLDA2
-
7/28/2019 DB2 Applications
98/167
SQLDATechnique 2
Allocate minimal SQLDA1 (SQLN = 0)
-
7/28/2019 DB2 Applications
99/167
SQLDAID SQLDABC SQLN SQLD
SQLTYPE SQLTYPE SQLDATA SQLIND SQLNAME
:
:
:
SQLN =
SQLD
SQLDAID SQLDABC SQLN SQLD
Allocate minimal SQLDA1 (SQLN 0)
DESCRIBE statement INTO SQLDA1 Read SQLD (#of columns returned)
Allocate large enough SQLDA2 (SQLN = SQLD)
-
7/28/2019 DB2 Applications
100/167
DESCRIBE statement INTO SQLDA2
Allocate host + Indicator variable storage OPEN CURSOR
FETCH
Notes:
This is the case where you have no idea at all about the number of returned columns or where you want to
use the same processing logic whatever that number may be.
SQLDA USAGESUMMARY
-
7/28/2019 DB2 Applications
101/167
Q
SQLDA
1.# of SQLVARs
allocated
SQLN
2. Description of
each selected
column
3. # of description
If DB2 sets SQLD to zero :
Statement is not a SELECT
Issue an EXECUTE
If DB2 sets SQLN to ZERO
SQLDA is too small to use
SQLD shows # of SQLVARs
needed
4. Addresses of
host +indicator
variables for each
selected column
SQLDATASQLIND
SQLD
SQLNAME
SQLTYPE
SQLLEN
COMMIT AND ROLLBACK
-
7/28/2019 DB2 Applications
102/167
COMMIT and ROLL BACK are not really database operations at all, in the sense that SELECT,
UPDATE are database operations.
The COMMIT and ROLLBACK statements are not instructions to the database management system.
Instead, they are instructions to the transaction manager and the transaction manager is certainly not
a part of the DBMS
On the contrary, the DBMS is subordinate to the transaction manager, in the sense that the DBMS is
just one of possibly several resourcemanagers that provide services to the actions running under
that transaction manager.
A transaction running under CICS can also use the services of three resources managers-
IMS/DB, CICS and DB2. Here CICS acts as the transaction manager.
In the TSO and purebatch environments, where DB2 itself serves as the transaction
manager, they are requested via the explicit SQL operators COMMIT and ROLLBACK
Before getting details of COMMIT and ROLLBACK statements as such, we first need to know
SYNCHRONIZATIONPOINT abbreviated as SYNCPOINT.
A SYNCPOINT represents a boundary point between two consecutive transactions, loosely speaking,
it corresponds to the end of a logical unit of work and thus to a point at which the database is in a
state of consistency. Program initiation, COMMIT and ROLLBACK each establish a synchpoint and
no other operation does.
COMMIT AND ROLLBACK (Cont...)
-
7/28/2019 DB2 Applications
103/167
( )
COMMIT :
The SQL COMMIT statement takes the form
COMMIT (WORK)
A successful end-of-transaction is signaled and a synchpoint is established. All updates made by
the program since the previous synchpoint are committed. All open cursors are closed, except for
cursors whose declaration includes the optional specification WITH HOLD , all rowlocks arereleased, except for locks needed to hold position for cursors not closed.
ROLLBACK
The SQL ROLLBACK statement takes the form
ROLLBACK [WORK]
An unsuccessful end-of-transaction is signed and a synchpoint is established. All updates made by
the program since the previous synchpoint are undone.
All open cursors are closed.
UNIT 5: HANDLING NULLS & ERRORS
SQLCA LAYOUT
-
7/28/2019 DB2 Applications
104/167
SQL CA layout REMARKS
SQLERRMLBINFIX(15)
SQLERRMC CHAR (70)
Length of error description
Short error description
SQLERRP CHAR(8)
SQLERRD(6) BIN FIX(31)
Diagnostic info (Module name)
Diagnostic into (Array)
SQLERRD(3) : number of rows that
were inserted, updated or deleted.
SQLWARNO CHAR(1)
SQLWARN1 CHAR(1)
SQLWARN2 CHAR(1)
SQLWARN3 CHAR(1)
SQLWARN4 CHAR(1)
If -> no warnings
Ifw -> warnings are present
Truncation of a string
NULL values eliminated from
argument of a function.
Number of cloumns is larger thannumber of host variables.
Delete or update stmt does not include
a WHERE clause
SQLAID CHAR(8)
SQLCABC BIN FIX(31)
SQLCODE BIN FIX(31)
SQLCA EYE CATCHER
Length of SQLCA (136)
Return code
SQLCA LAYOUT
SQLCA LAYOUT
-
7/28/2019 DB2 Applications
105/167
SQLCA LAYOUT
Error handling is based on information, DB2 returns in the SQLCA (SQL Communication
Area). The most important fields are the SQLSTATE and SQLCODE.
SQLSTATE
-
7/28/2019 DB2 Applications
106/167
SQLSTATE is an SQL return code contained in a 5 digit character string.
First digit : zero (successful) or not Zero
First 2 digits : SQLSTATE CLASS
01 : unqualified successful execution
02 : warning
03 : warningno data
last 3 digits represent SQLSTATE SUBCODE
Example :
SQLSTATE 00000 : successful
SQLSTATE01501 : string truncation
SQLSTATE 02000: no more data
Notes:
SQLSTATE is a return code that is common to all DB2 family products. If you base your error
handling on SQLSTATE, your interpretation of the error situation will be independent of the
platform where the SQL statement was actually executed.
It is recommended, therefore to use SQLSTATE instead of SQLCODE.
-
7/28/2019 DB2 Applications
107/167
SQLCA CODES USAGE
St t i f ti i i b
-
7/28/2019 DB2 Applications
108/167
CONDITION INTEGER
SQLCODE
Char(5)
SQLSTATE
Char(1)
SQLWARNO
REQUEST
STATUS
Error < 0 = 00000 = 01ddd
= 02000
Failed
Warning > 0&
= 100
01dddd Or w
Satisfied, with
special
conditions
Not found+100 02000 (more)
data not found
Success 0 00000 And Success
Status information is given by :
SQLCODE, SQLSTATE and
SQLWARNO SQLWARN1SQLWARNA
Notes:
The chart gives you a general overview of which return codes will be generated in the indicated warning or
error situation.
ERROR HANDLINGExample of testing return codes :
-
7/28/2019 DB2 Applications
109/167
Example of testing return codes :
Example of using WHENEVER
EXEC SQL SELECT
IF SQLSTATE = 00000THEN IF SQLSTATE = 02000
THEN DISPLAY RECORD NOT FOUND
ELSE IF SUBSTR (SQLSTATE,1, 2) = 01
THEN DISPLAY WARNSQL
ELSE DISPLAY ERRORSQL
ELSE
:
:
EXEC SQL WHENEVER NOT FOUND GOTO NO MORE
EXEC SQL WHENEVER SQLERROR GOTO ERRORSQL
EXEC SQL WHENEVER SQLWARNING GOTO WARNSQL
:
:
:
EXEC SQL SELECT..
:
ERROR HANDLING (Cont)
-
7/28/2019 DB2 Applications
110/167
( )
Various techniques can be used to detect error conditions. One thing is sure : you need errorhandling. The first technique is to react individually after every SQL statement. A more
general error routine should be developed and called after each SQL statement.
The second technique, WHENEVER, is not recommended for general use.
SCOPE OF WHENEVER
-
7/28/2019 DB2 Applications
111/167
SCOPE OF WHENEVER
PreProcessorflow
Execution
flowSoruce
code
EXEC SQL WHENEVER SQLERROR GOTO LAB1
:
EXEC SQL SELECT
IF SQLCODE < 0 THEN GOTO LAB
:
LAB1
:
EXEC SQL WHENEVER SQLERROR GOTO LAB2
:
-
7/28/2019 DB2 Applications
112/167
ERROR MESSAGE FORMATTING ROUTINE
-
7/28/2019 DB2 Applications
113/167
SQLCA
Error Information
Size of
message area
Output
Error message
Built by
DSNTIAR
Length of message
line
SMALLINTINTEGER
ERROR Message Formatting Routine :
CALL DSNTIAR
And pass it three areas :
- FORTRAN uses routine DSNTIR
Notes:
Attention should be paid not to invoke DSNTIAR unless an error condition is detected,
because the module is dynamically loaded into storage when invoked. If you do this without
care, you will waste a lot of resources.
ERROR HANDLING - GENERAL
-
7/28/2019 DB2 Applications
114/167
WHENEVER will in general not be used
Different treatment needed for NOT FOUND after delete/ update/ insert.
Coming back after WHENEVER
Might want to intercept other return codes
SYSADM will normally provide a STANDARD error routine for everyone to use
Only CALL DSNTIAR in error condition.
Notes:
As mentioned previously, the use of WHENEVER is not recommended, and we advise using a general error
routine that is called after each SQL statement
RETRIEVING NULL VALUES
-
7/28/2019 DB2 Applications
115/167
:REF1:REF2
01 P-PHONE PIC X(4) /*H-VARIABLE */
01 P-PHONE-I PIC S9(4) COMP /*I-VARIABLE*/
EXEC SQL SELECT PHONENO
INTO :P-PHONE : P-PHONE-I
FROM EMP
WHERE EMPNO = :INP-EMP
END-EXEC.
Indicator Variable (:REF2) should always be provided if selected column allows
NULL
After the SELECT
If PHONENO contains the NULL value :
H-variable P-PHONE -> unchanged
I- variable P-PHONE -> negative
If PHONENO contains data :
H-variable P-PHONE -> updated
I- variable P-PHONE -> not negative
-
7/28/2019 DB2 Applications
116/167
Notes :
If a column can contain the NULL value, a special host variable called an IndicatorVariable should be
defined in the program. This variable is used by DB2 to signal the existence of a NULL value for that column.
INSERTING NULL VALUES
Definition of Host Variables :
-
7/28/2019 DB2 Applications
117/167
01 PEMPL.02 EMPNO PIC X(06).
02 FIRSTNME PIC X(12).
02 MIDINITPIC X(01).02 LASTNAME PIC X(15).
02 WORKDEPT PIC X(03).
02 PHONENOPIC X(04).
01 PEMPL.
10 INDSTRUC PIC S9(4) COMP OCCURS 6 TIMES
IF no_phone_number_exists, THEN
NPHONE = -1.
EXEC SQL
UPDATE PEMPL
SET PHONENO = : PHONENO : PHONENO
WHERE EMPNO = :EMPNO
END-EXEC.
Definition of Indicator Variable :
Set Indicator Variable :
Imbedded SQL :
Notes: On the other hand, the indicator variable will allow you to pass a NULL value to DB2.
SELECTING NULL VALUES
-
7/28/2019 DB2 Applications
118/167
IF null_value_wanted, THEN
NPHONE = -1.
EXEC SQL SELECT LASTNAME, FIRSTNME
FROM PEMPL
WHERE PHONENO =:NPHONE
END-EXEC.
EXEC SQL SELECT LASTNAME, FIRSTNME
FROM PEMPL
WHERE PHONENO IS NULL
END-EXEC.
If the indicator variable NPHONE is set to a negative value, the statement istreated as
and the contents of the host variable PHONENO is ignored.
Notes:
A negative value set in the indicator variable indicates a NULL value for the associated host variable.
HOST STRUCTUREINDICATOR VARIABLE
Definition of host variable (Structure) :
-
7/28/2019 DB2 Applications
119/167
01 PEMPL.
02 EMPNO PIC X(06).
02 FIRSTNME PIC X(12).
02 MIDINITPIC X(01).02 LASTNAME PIC X(15).
02 WORKDEPT PIC X(03).
02 PHONENOPIC X(04).
01 PEMPL.
10 INDSTRUC PIC S9(4) COMP OCCURS 6 TIMES.
EXEC SQL SELECT *
INTO :PEMPL :INDSTRUC
FROM PEMPL
WHERE EMPNO = :EMPNO
END-EXEC.
IF INDSTRUC(5) < 0 THEN
WORKDEPT = ???? THEN
IF INDSTRUC(6) < 0 THEN
PHONENO = UNKN
( )
Definition of Indicator Variable (array) :
Imbedded SQL :
Test for NULL Values :
-
7/28/2019 DB2 Applications
120/167
HANDLING ARITHMETIC ERRORS
-
7/28/2019 DB2 Applications
121/167
Arithmetic error exceptions will be tolerated, if error occurs in the select list of the
Outer SELECT and an indicator variable
Result of expression is NULL
Indicator variable is set to -2
SQLSTATE 01519 returned in the SQLCA ( SQLCODE +802)
Value in host variable left unchanged
Processing continues
Expressions and values not in error will be returned.
Otherwise statement execution will be halted and SQLSTATE 22013 OR 22003
(SQLCODE802) WILL BE RETURNED
Notes:
Indicator variables are also used by DB2 to signal arithmetic error conditions.
HANDLING CONVERSION ERROR
-
7/28/2019 DB2 Applications
122/167
If a conversion error occurs in an embedded SELECT OR FETCH statement and an
indicator variable has been provided for the expression.
Result of expression is NULL
Indicator variable is set to -2
SQLSTATE 01515 returned in the SQLCA (SQLCODE =-304)
Value in host variable left unchanged
Processing continues
Expressions and values not in error will be returned
Otherwise statement execution will be halted and SQLSTATE 22003
(SQLCODE304) will be returned
Notes:
Indicator Variable are also used by DB2 to signal conversion errors.
ARITHMETIC AND CONVERSION ERROR EXAMPLES
-
7/28/2019 DB2 Applications
123/167
Example Background :
Declaration In program
01 MV1 PIC S9(4) COMP.
01 MV2 PIC S9(4) COMP.
01 MV3 PIC S9(4) COMP.
01 MV11 PIC S9(4) COMP.
01 MV21 PIC S9(4) COMP.
01 MV31 PIC S9(4) COMP.
01 IV1 PIC S9(4) COMP. /* Indicator Variable */
01 IV2 PIC S9(4) COMP. /*Indicator Variable */
01 IV3 PIC S9(4) COMP. /* Indicator Variable */
TABLE A values are
-
7/28/2019 DB2 Applications
124/167
TABLE A values are
Notes :
Note the contents of the table and program definitions used for the coming examples
SM1 INT1 SMI2
1
2
3
4
123458
345678
123678
211111111
1
0
1
4
EXAMPLE OF ARITHMETIC ERRO
EXEC SQL
-
7/28/2019 DB2 Applications
125/167
EXEC SQL
SELECT SMI1,SMI1*INTI, SMI1/SMI2
INTO :MV1 : IV1, :MV2:IV2, :MV3:IV3
FROM TABLEAEND-EXEC.
Result for first row : MV1 = 1 IV1 = 0
MV2 = 123458 IV2 = 0
MV3 = 1 IV3 = 0
SQLSTATE = 00000
Result for Sec row : MV1 = 2 IV1 = 0
MV2 = 691356 IV2 = 0
MV3 = 2/0 IV3 = -2
SQLSTATE = 01519
Result for third row : MV1 = 3 IV1 = 0
MV2 = 371034 IV2 = 0MV3 = 3 IV3 = 0
SQLSTATE = 00000
Result for forth row : MV1 = 4 IV1 = 0
MV2 = 844444444 IV2 = -2
MV3 = 1 IV3 = 0
SQLSTATE = 01519
-
7/28/2019 DB2 Applications
126/167
OTHER ERROR CONDITIONS
-
7/28/2019 DB2 Applications
127/167
TABLE CHECK Constraint
22513 / - 545statement not executed
VIEW CHECK option
23501 / - 161
statement not executed
DATE Invalid
22007 / -180 0r -181
statement not executed
Notes:
A smart program could also handle those error condition. ABENDing the program is not always needed.
-
7/28/2019 DB2 Applications
128/167
STORED PROCEDURES: FLOW
-
7/28/2019 DB2 Applications
129/167
DB2
PROCX
EXEC SQL
SELECT.FROM
WHERE COL1 = : IN
EXEC SQL DELETE
EXEC SQL UPDATE
EXEC SQL INSERT
OUT = RESULT
Proc end
Client Program
EXEC SQL CALL Procx
(In, Out);
Notes :
A Stored procedure is a program that is controlled by DB2 that can be called through an SQL
statement. The program can receive parameters and also has the ability to return data to the calling
application.
STORED PROCEDURES: CONSIDERATIONS
-
7/28/2019 DB2 Applications
130/167
RUN IN LE/370 ENVIRONMENT
CODED IN ANY LANGUAGE(COBOL ,PL1, C)
BEST TO CODE REENTRANT
CAN NOT
ISSUE CAF CALLS
CALL OTHER STORED PROCS
COMMIT/ROLLBACK
CONNECT
CAN USE NON-DB2 RESOURCE WITHOUT 2-PCS
MUST BE DEFINED IN THE CATALOG
CLIENT CAN BE LOCAL OR REMOTE
STORED PROCEDURES: CONSIDERATIONS (Cont...
Both client and server applications can be written in any programming language. To make it a
-
7/28/2019 DB2 Applications
131/167
Both client and server applications can be written in any programming language. To make it a
truly open concept, DB2 supports any type of client. The client can, in fact, be any application that
can use either directly DB2 for MVS or that can pass calls to a DRDA application requester. The
client and server are both shielded from any language differences by means of the LE/370environment.
All SQL executed within the stored procedure will be considered to be within the same logical
unit of work as the client application. DB2 will, therefore, coordinate the potential changes with the
UOW of the calling application. This feature restricts the use of SQL-statements such as COMMIT
and ROLLBACK. Since stored procedures run using the CAF (Call Attachment Facility), you willnot be able to issue any CAF calls.
In the current implementation of DB2, there is only one address space that will run the
procedures. It is, therefore, best to code the procedures as being reentrant, which will enable the
parallel execution of the program. If it is not reentrant, only one user can use the procedure at a
certain point in time.
The stored procedure could also access non-DB2 data such as CICS transactions.
That environment, however, is not going to be included in the same logical unit of work. There is
no two-phase commit support with the other environments. Interfaces the stored procedure can use
are: The MQI interface (Message Queuing) for asynchronous execution, or the EXCI (External
CICS interface) for synchronous execution of CICS transactions.
STORED PROCEDURES: CALL SYNTAX
-
7/28/2019 DB2 Applications
132/167
CALL ---procedure- name -----------------------------------------------------------------------------
Host- variable -----------------------------------------------------------------------
Host-variable
Constant
NULL
USING DESCRIPTOR NAME
EXEC SQL CALL A (:EMP, :PRJ, :ACT)
EXEC SQL CALL A (:EMP :INDEMP, : PRJ :INDPRJ, :ACT :INDACT)
EXEC SQL CALL A (103455,BUIL5, :ACT)
EXEC SQL CALL A USING DESCRIPTOR :SQLDA
EXEC SQL CALL : PROCNAM USING DESCRIPTOR : SQLDA
Notes:
A number of different ways exist. Bottom line is that you can use all options as host variables, both the
name of the procedure and the parameters that are passed to it.
STORED PROCEDURES : LINKAGE CONVENTIONS
-
7/28/2019 DB2 Applications
133/167
SIMPLE LINKAGE
Parameter 1, Parameter 2 , Parameter 3,
Parameter 1 Null Indicator 1, Parameter 2 Null Indicator 2 , Parameter 3 Null Indicator 3, ..
IN IN
OU
T
OU
T
SIMPLE WITH NULL LINKAGE
Notes: Two linkage conventions can be used:
SIMPLE :
This type of linkage only allows the use of null for parameters that are defined as output parameters. For the
output parameters you can add an indicator Variable. If that variable is set to a negative value, DB2 will not
pass the whole variable to the procedure. This technique will help improve the speed of the call, as DB2 has
less information to send.
STORED PROCEDURES : LINKAGE CONVENTIONS (Cont..)
-
7/28/2019 DB2 Applications
134/167
SIMPLE WITH NULL : This type of linkage will require a null indicator for all parameters
regardless of whether they are IN, OUT or INOUT.
For both types of linkages, you will have to define the nature of the parameter, which can be:
IN (this parameter contains no value upon return from the procedure)
OUT (the content is not passed along to the procedure)
INOUT (data flows in both directions)
STORED PROCEDURES : DB2 SETUP
PROCEDURE : Name of the procedure
AUTHID : Userid
-
7/28/2019 DB2 Applications
135/167
AUTHID : Userid
LUNAME : Luname this entry is intended for
LOADMODULE : Name of the program used for this procedure
COLLID : Collection in which the package is stored
LINKAGE : SIMPLE or SIMPLE WITH NULLS
LANGUAGE : Programming language used to code the program
RUNOPTS : Any option you want to pass to the LE/370 environment.
PARMLIST : Complete description of the parameter list
ASUTIME : Maximum amount of CPU service units one run can consumeSTAYRESIDENT : Program stays in storage after it has completed
IBMREQ : Is this an IBM or a User entry.
ININ
OU
T
OU
T
Parameter 1 Null Indicator 1, Parameter 2 Null Indicator 2, Parameter 3 Null Indicator,
STORED PROCDEURES: DB2 SETUP (Cont.)
-
7/28/2019 DB2 Applications
136/167
To allow DB2 to know where and how the stored procedure is to be used, you will have to
make an entry in a catalog table. This entry will give a description of who can use the
procedure and what parameter conventions are used to call the procedure.
You can specify different definitions for the same procedure based on the calling LU-name
and use rid. The will allow you to test a new procedure while the old one is still used.
The parm list has to contain a description of all the parameters that are included in the call
and, of course, whether they are IN, OUT or INOUT.
The ASUTIME column allows you to put a limit on the amount of resources that can be
consumed by one invocation of a stored procedure.
UNIT 7: DB2 UTILITIES
-
7/28/2019 DB2 Applications
137/167
OVERVIEW
CATEGORIES OF DB2 UTILITIES
LOAD UTILITY
CATEGORIES OF DB2 UTILITIES
-
7/28/2019 DB2 Applications
138/167
DATA CONSISTENCY UTILITIES
BACKUP AND RECOVERY UTILITIES.
DATA ORGANIZATION UTILITIES.
CATALOG MANIPULATION UTILITIES
DATA CONSISTENCY UTILITIES
The Consistency of data in a database is paramount important and so it must be controlled
i i i i i i i i
-
7/28/2019 DB2 Applications
139/167
and monitored. The data consistency utilities are used to monitor, control and administer the
data consistency errors.
Three Data consistency utilities
CHECK
REPAIR
REPORT
CHECK:
The CHECK utility checks the integrity of data structures. It has two purposes.
The first is to check the referential integrity between two tables, displaying and potentially
resolving referential constraint violation.
The second purpose of the CHECK utility is to check DB2 indexes for consistency.
This consists of comparing the key values of the indexed columns to their corresponding table
values, as well as evaluating the RIDs in the tables and indexes being checked.
The CHECK utility has two options CHECK DATA and CHECK INDEX.
DATA CONSISTENCY UTILITIES (Cont.)
REPAIR:
-
7/28/2019 DB2 Applications
140/167
The REPAIR utility is designed to modify DB2 data and associated data structures when there is
an error or problem.
There are 3 distinct uses
The first is to test the DBD definitions in the DB2 directory and to synchronies the DB2
catalog database information with the DB2 directory and the DBD definition.
The second is to physically change specific locations in a data set.
The third and final type of REPAIR is to reset pending flags that are erroneously set.
REPORT:
Two types of reports can be generated with the REPORT UTILITY.
The first is a table space set report showing the names of all tables spaces and table spaces
and tables tied together by referential integrity.
The second type of REPORT utility, the REPORT RECOVERY can be used to generate a
report on table space recovery information.
BACKUP AND RECOVERY UTILITIES
The back p and reco er tilities s pplied ith DB2 are er comple The remo e the
-
7/28/2019 DB2 Applications
141/167
The backup and recovery utilities supplied with DB2 are very complex. They remove the
burden of database recovery from the DBA and place it with the DBMS. The main backup
and recovery utilities are
COPY
MERGECOPY
RECOVER
COPY:
The COPY utility is used to create an image copy, back up data set for a complex table space
or a single partition of an all space.
MERGECOPY:
The MERGECOPY utility combines multiple incremental image copy data sets into a new full
or incremental image copy data set.
RECOVER:
The RECOVER utility is used to restore DB2 table spaces and indexes to a specific point in
time. You can run two forms of RECOVER utility. RECOVER TABLESPACE and
RECOVER INDEX. The RECOVER TABLESPACE restores table spaces to a current or
previous state, whereas the RECOVER INDEX utility can be used to re-create, indexes from
current data.
DATA ORGANIZATION UTILITIES
-
7/28/2019 DB2 Applications
142/167
The data organization utilities affect the physical data sets of the DB2 objects for which they
are run. Rows of data and their sequence are affected by these utilities. There are 2 data
organization utilities
LOAD
REORG
LOAD:The LOAD utility is used to accomplish bulk inserts to DB2 tables. It can add rows to a table
retaining the current data or it can replace the existing rows with new data.
REORG:
The REORG utility can be used recognizes DB2 table spaces and indexes thereby improving
the efficiency of the access to those objects. Reorganization also re-clusters data, resets free
space to amount specified in the CREATE DDL and delete and redefines the underlying
VSAM data sets for STOGROUP defined object.
CATALOG MANIPULATION UTILITIES
-
7/28/2019 DB2 Applications
143/167
The DB2 catalog and directory are essential for the proper functioning of the DB2 subsystem.
It has RUNSTATS utility.
RUNSTATS:
The RUNSTATS utility collects statistical information for DB2 tables, table spaces,
partitions, indexes and columns.
It can place this information into the DB2 Catalog Tables. The DB2 optimiser for
determining the optimal access paths for the SQL queries reads the tables.
The information can be queried using SQL statements.
DATA UTILITIESLOAD
-
7/28/2019 DB2 Applications
144/167
LOAD - Loads the records in INPUT SEQUENCE in one or more tables of the same table
spaces.
Sequential
Dataset
LOAD
Table space
Index
Notes:
Besides the CHECK DATA UTILITY, we also have load utility. It provides a way to LOAD a self-
referencing table.
Load will load the input records from the sequential file in input file record sequence.
LOADING DATA IN ONE TABLE
POSITION (36)
CHAR (6)
-
7/28/2019 DB2 Applications
145/167
01..234.
E21 SOFTWAR SUPPORT031435 E01
TABLE
DEPT
CHAR (6)
DEPTNO DEPTNAME MGRNO ADMRDEPT
E21 SOFTWARESUPPORT
031435 E01
LOAD DATA
INTO TABLE DEPT
(DEPTNO POSITION (7) CHAR (3),
(DEPTNAME POSITION (10) CHAR (26),
(MGRNO POSITION (36) CHAR (6),
(ADMRDEPT POSITION (42) CHAR (3))
TARGET COLUMN INPUT FIELD LOCATION INPUT FIELD TYPE AND LENGTH
DATA TYPE CONVERSION
Suppose that
- MGRNO was defined as INTEGER in the DEPT table, and
-
7/28/2019 DB2 Applications
146/167
- The input dataset is identical to the one in the previous example.
Character Format
01..234.
E21 SOFTWAR SUPPORT031435 E01
Defined as INTEGER when
CREATE TABLE was performed
DEPTNO DEPTNAME MGRNO ADMRDEPT
E21 SOFTWARE
SUPPORT
031435 E01TABLE DEPT
LOAD DATAINTO TABLE DEPT
(DEPTNO POSITION (7) CHAR (3),
(DEPTNAME POSITION (10) CHAR (26),
(MGRNO POSITION (36) INTEGER-EXTERNAL(6),
(ADMRDEPT POSITION (42) CHAR (3))
-
7/28/2019 DB2 Applications
147/167
Note:
In some cases, the data types of the input record field and the target column dont match. In the example, the
INTEGER EXTERNAL keyword tells DB2 that the record field contains numeric data formatted as
characters. The LOAD utility will perform the necessary data conversion.
LOADING NULL VALUES
Setting columns to default values
0 1 2 3 4
-
7/28/2019 DB2 Applications
148/167
01..234.
E21 SOFTWAR SALES ??????? E01
DEPTNO DEPTNAME MGRNO ADMRDEPT
E21 SOFTWARE
SALES
--------- E01
The MGRNO column allows NULL values so NULL values So NULL is its default.
LOAD DATA
INTO TABLE DEPT
(DEPTNO POSITION (7:9) CHAR ,
(DEPTNAME POSITION (10:35) CHAR,
(MGRNO POSITION (36:41) CHAR
DEFAULT (36:41) = ????????.
(ADMRDEPT POSITION(42:44)CHAR(3))
A recognizable string of question marks is used in this example to trigger the loading of NULL values in
the column.
TABLE DEPT
LOADING MULTIPLE TABLES IN A TABLESPACE
Loading different tables by testing an input field :
-
7/28/2019 DB2 Applications
149/167
Loading different tables by testing an input field :
LOAD DATAINTO TABLE DEPT
WHEN (51) = D
(DEPTNO POSITION(7) CHAR(3),
DEPTNAME POSITION
.
top related