Documente Academic
Documente Profesional
Documente Cultură
1.
2.
INTRODUCTION......................................................................................................2
2.1.
DATABASE MANAGEMENT SYSTEMS (DBMS)..................................................3
2.2.
TYPES OF DBMS............................................................................................. 4
2.2.1.
Relational DBMS......................................................................................4
2.2.2.
HIERARCHICAL DBMS...........................................................................6
2.2.3.
Net Work DBMS........................................................................................7
2.3.
SAMPLE DB2 DATABASE................................................................................... 8
3.
STRUCTURE OF DB2..............................................................................................9
3.1.
HIERARCHY OF DATA STRUCTURES..................................................................9
3.2.
DATABASES...................................................................................................... 9
3.3.
DB2 STORAGE GROUPS.................................................................................... 9
3.4.
TABLE SPACES.................................................................................................. 9
3.4.1.
Simple Tablespace.....................................................................................9
3.4.2.
Segmented Table Space.............................................................................9
3.4.3.
Partitioned Table Space............................................................................9
3.5.
TABLES............................................................................................................ 9
3.6.
INDEX SPACES.................................................................................................. 9
3.7.
INDEXES........................................................................................................... 9
3.8.
VIEWS.............................................................................................................. 9
3.9.
SYNONYMS...................................................................................................... 9
3.10. ALIASES........................................................................................................... 9
3.11.
DB2 CATALOG.................................................................................................. 9
3.12. DB2 DIRECTORY.............................................................................................. 9
3.13. ACTIVE AND ARCHIVE LOGS............................................................................9
3.14. BUFFER POOLS................................................................................................. 9
4.
DATA TYPES............................................................................................................39
4.1.
NUMERIC DATA.............................................................................................. 39
4.1.1.
Nulls........................................................................................................39
4.2.
STRING DATA.................................................................................................. 39
4.3.
CHARACTER FORMAT..................................................................................... 39
4.4.
DATE/TIME DATA........................................................................................... 39
4.5.
EQUIVALENT COBOL DECLARATIONS OF DATA TYPES....................................39
5.
SQL PROGRAMMING..........................................................................................49
5.1.
DDL STATEMENTS.......................................................................................... 51
5.1.1.
Create Database......................................................................................51
5.1.2.
Create Table Space..................................................................................51
5.1.3.
Create Table............................................................................................51
5.1.4.
Create View..............................................................................................51
5.1.5.
Create Index............................................................................................51
5.1.6.
Alter Table...............................................................................................51
5.1.7.
Drop........................................................................................................51
5.2.
DML STATEMENTS......................................................................................... 64
5.2.1.
Select.......................................................................................................64
DB2 Fundamentals
5.2.2.
Joining Tables.........................................................................................64
5.2.3.
Sub Queries.............................................................................................64
5.2.4.
Union.......................................................................................................64
5.2.5.
Insert.......................................................................................................64
5.2.6.
Update.....................................................................................................64
5.2.7.
Delete......................................................................................................64
5.3.
CONTROL STATEMENTS................................................................................... 82
5.3.1.
Grant.......................................................................................................82
5.3.2.
Revoke.....................................................................................................82
5.3.3.
Commit....................................................................................................82
5.3.4.
Roll Back.................................................................................................82
6.
PROGRAM STRUCTURE.....................................................................................87
6.1.
HOST VARIABLES........................................................................................... 87
6.1.1.
Declaring Host Variables........................................................................87
6.2.
INDICATOR VARIABLES................................................................................... 87
6.3.
SQLCA.......................................................................................................... 87
6.4.
COBOL STRUCTURE OF SQLCA.....................................................................87
6.5.
SQLCA RETURN CODES................................................................................. 87
6.6.
SQLCA WARNINGS........................................................................................ 87
6.7.
IMPORTANT SQL CODES.................................................................................87
6.8.
STATIC SQL.................................................................................................... 87
6.9.
DYNAMIC SQL............................................................................................... 87
6.10. EXAMPLE FOR A DB2 APPLICATION PROGRAM...............................................87
7.
PROGRAM PREPARATION...............................................................................122
7.1.
STEPS IN PROGRAM PREPARATION................................................................122
7.2.
DCLGEN (DECLARATIONS GENERATOR )......................................................122
7.3.
PRECOMPILE................................................................................................. 122
7.4.
BIND............................................................................................................ 122
7.4.1.
Binding A DBRM To A Package............................................................122
7.4.2.
Binding An Application Plan................................................................122
7.5.
COMPILE AND LINKEDIT............................................................................... 122
7.6.
OVERVIEW OF DB2 APPLICATION PROGRAM PREPARATION AND EXECUTION
122
7.7.
ASSOCIATING LOAD MODULES AND PACKAGES............................................122
8.
SECURITY FEATURES.......................................................................................140
8.1.
PRIVILEGES................................................................................................... 140
8.2.
REFERENTIAL INTEGRITY.............................................................................. 140
8.2.1.
DB2 Enforcement Of Referential Integrity...........................................140
8.2.2.
Referential Integrity Enforcement Rules...............................................140
8.2.3.
Example For Referential Integrity Violation.........................................140
8.3.
DATABASE RECOVERY IN CASE OF FAILURE................................................140
8.3.1.
Unit Of Recovery...................................................................................140
8.3.2.
Data Recovery.......................................................................................140
9.
CONCURRENCY..................................................................................................157
9.1.
9.2.
9.3.
9.4.
9.5.
CONCURRENCY............................................................................................ 157
LOCKING STRATEGY..................................................................................... 157
LOCK SIZES AND TYPES...............................................................................157
ACQUIRE RELEASE PARAMETERS..................................................................157
ISOLATION PARAMETER................................................................................ 157
ii
DB2 Fundamentals
10.
10.1.
10.2.
11.
11.1.
11.2.
11.3.
12.
iii
DB2 Fundamentals
1.
The Purpose of this document is to train fresh Software Engineers who would like to get
familiarized with DB2 and as a reference material for application programmers.
1.1.
2.
Introduction
DB2 FOR
OS/2
DB2 FOR
AIX
DB2 FOR
HP-UX
DB2 FOR
SOLARIS
DB2 FOR
WINDOWS /NT
DB2 FOR
SINIX
DB2 FOR
MVS
DB2 FOR
VSE & VM
DB2 FOR
OS/400
2.1.
DBMS
DATABASE
APPLICATION
QUERY
PROGRAM
PROCESSOR
STORAGE MANAGER
DATA
AVOID INCONSISTENCY
SHARE DATA
MANIPULATES DATA EFFICIENTLY
FAULT TOLERANT
DATA INDEPENDENCE
2.2.
Types Of DBMS
Depending on data models used, database management systems are mainly divided into
three.
RELATIONAL DBMS
HIERARCHICAL DBMS
NETWORK DBMS
TABLE SP
SNAME
S1
S2
S3
SMITH
JONES
BLAKE
STATUS
20
10
30
CITY
LONDON
PARIS
PARIS
TABLE P
P#
PNAME
COLOR
P1
P2
P3
P4
NUT
BOLT
SCREW
SCREW
RED
GREEN
BLUE
RED
WEIGHT
12
17
17
14
CITY
LONDON
PARIS
ROME
LONDON
S#
P#
QTY
S1
S1
S1
S2
S2
S3
P1
P2
P3
P1
P2
P2
300
200
400
300
400
200
PARTS DATABASE
S1
P1
S2
..
SMITH
NUT
JONES
20
RED
12
LONDON
10
LONDON
SHIPMENTS DATABASE
PARIS
SHIPMENT
SEGMENT
LCHILD
In this view data is represented by a simple TREE STRUCTURES and DBMS links
these data bases using pointers.
The user sees three individual trees for supplier database, each tree has a parent
supplier. Each tree can be called a supplier record occurrence. Similarly you can see
part record occurrence and shipment record occurrence.
Shipment database contains the shipment quantity. The logical child of shipment
database consists of supplier number , part number and pointers to corresponding
databases .Similarly the supplier and parts databases also contains logical child which
points to the shipment database. Now the user can access shipment from supplier and
part databases. Similarly parts and supplier databases are also accessed from shipment
database
IMS (Information management system) is an example of Hierarchical DBMS
SUPPLIER
RECORD SET
PART RECORD
SET
S1 SMITH..
P1 NUT ..
S2 JONES..
P2 BOLT.
QUANTITY RECORDS
300
400
.
NETWORK DBMS consists of owner databases and member databases. The member
database can be accessed only via the owner database.
In the example there are two owners for a member database. Supplier and part record
sets are owners of shipment record set. Using this database the user can access the
shipment of a particular part by a specific supplier
The supplier S1 supplies part P1 of quantity 300. From the supplier S1 there is a
pointer towards the supplied quantity and another pointer connects this to the
corresponding part. An owner can have more than one pointer towards different
quantities.
Example of network database is IDMS(Integrated database management system)
2.3.
The sample database consists of THREE tables and these tables are used through out this
book.
TABLE S
TABLE SP
S#
SNAME
STATUS
S1
S2
S3
S4
S5
SMITH
JONES
BLAKE
CLARK
ADAMS
20
10
30
20
30
TABLE P
P#
PNAME
P1
P2
P3
P4
P5
P6
NUT
BOLT
SCREW
SCREW
CAM
COG
CITY
P#
QTY
S1 P1
PARIS
S1 P2
200
PARIS
S1 P3
400
LONDON
S1 P4
ATHENS
S1 P5
S1 P6
S2 P1
S2 P2
S3 P2
COLOR WEIGHT
CITY
S4
P2
S4
P4
RED
12
LONDON
S4
P5
GREEN
17
PARIS
BLUE
17
ROME
RED
14
LONDON
BLUE
12
PARIS
RED
19
LONDON
300
LONDON
S#
200
100
100
300
400
200
200
300
400
3.
Structure Of DB2
This chapter deals with the definitions and examples of objects present in DB2.The topics
included in this chapter are
3.1.
3.2.
Databases
3.3.
3.4.
Table Spaces
Tables
3.6.
Index Spaces
3.7.
Indexes
3.8.
Views
3.9.
Synonyms
3.10. Aliases
3.11.
DB2 Catalog
STRUCTURE OF DB2
SYSTEM STRUCTURES
DB2 CATALOG
DB2 DIRECTORY
ACTIVE AND ARCHIVE LOGS
BUFFER POOLS
STORAGE GROUP
G1
TABLE SPACE S1
TABLE T1
TABLE T2
VOLUME 1
(DASD)
INDEX X1
VOLUME 2
(DASD)
INDEX X2
PARTITIONED
TABLESPACE
S2
TABLE T3
PART 1
TABLE T3
PART 2
STORAGE
GROUP G2
VOLUME2
(3380)
PARTITIONED INDEX X3
PART 1
PARTITIONED INDEX X3
PART 2
DATA BASES
DATABASE1
TABLESPACE1
INDEX 1
TABLE 1
TABLE 2
INDEX 2
TABLESPACE 2
WHEN YOU
STORAGE GROUP 1
VOLUME 1
VOLUME 2
TABLE SPACES
TABLESPACE 1
TABLE 1
TABLE 2
SIMPLE
SEGMENTED
PARTITIONED
Table Spaces
A TABLE SPACE can be thought of as a logical address space on secondary storage that is
to hold one or more stored tables. Table spaces are divided into equal sized units called
PAGES which are written or read from DASD. Tables are physically stored in one or more
VASM linear datasets.
A table space can consists of 1 to 64 VSAM datasets which can together contain up to 64
GIGABYTES of data. When you create a table space you can specify the database and
storage group to which the tablespace belongs and table space type. As the amount of data
in tables grow storage will be acquired from appropriate storage groups and added to the
tablespace.
Fundamentally the table space is a storage unit for recovery and reorganization. If the table
space is very large the RECOVERY and REORGANIZATION could take a long time.
Hence making the tablespace simple, segmented, or partitioned can drastically affect the
performance.
SIMPLE TABLESPACE
SIMPLE TABLESPACE
FREE
PAGE
FREE
SPACE
4K
PAGE
RECORD OF TABLE 1
RECORD OF TABLE 2
Simple Tablespace
In simple table space records of tables are interleaved .Records of different tables may be
present in a single page and to find all rows of a table a scan of the whole table space is
needed. But by loading the data in an appropriately interleaved manner; accessing logically
related data will be more efficient.
If a table is dropped, its rows are not deleted. The space occupied by the rows does not
become available until the table space is reorganized. All tables in a simple table space must
reside in the same user-defined data set or in the same storage group.
one stored table per table space is always the most satisfactory arrangement in the case of
simple TABLE SPACE.
SEGMENTED TABLESPACE
SEGMENT1
SEGMENT2
4K
PAGE
SEGMENT3
Segmented Tablespace
In a SEGMENTED TABLESPACE the tablespace is divided into segments and each
segment consists of a logically contiguous set of N PAGES. N must be a multiple of 4 in
the range 4 TO 64 and is same for all segments in the table space. The size of the segment
is specified while creating the tablespace.
Each segment in the segmented tablespace contains rows from only one table. But the
tablespace can contain multiple tables, in different SEGMENTS. In order to find a row, it is
not necessary to scan the entire table space, but only the segments that contain the table.
Hence sequential access to a particular table is more efficient.
If a table in a segmented table space is dropped, the space for that table can be reused
without performing a reorganization of the table space.
A segmented table space can have between 1 AND 32 VSAM linear data sets. the
maximum size of a data set in the segmented table space is 2 GIGABYTES and so, the
maximum size of a segmented table space is 64 GIGABYTES .
PARTITIONED TABLESPACE
AF
PARTITION1
GP
PARTITION2
QZ
PARTITION3
RECORD OF TABLE 1
Partitioned Tablespace
PARTITIONED TABLESPACES are intended for stored tables that are sufficiently large.
Partitioned table contains exactly one stored table, partitioned in accordance with value
ranges of a particular column or column combination .
A partition can be 1, 2, OR 4 GIGABYTES in length, depending on the number of
partitions contained in the entire table space. If only one partition is defined on the table
space, then its MAXIMUM SIZE IS 4 GIGABYTES.
Partitioning a table space provides several advantages for large tables. When DB2 scans
data to answer a query it can scan through partitions simultaneously instead of scanning
through the entire table from the beginning to end.
A utility can work on all partitions simultaneously instead of working on one partition at a
time. Also, different utilities can work on different partitions simultaneously. This can
significantly reduce the amount of time needed for a utility to finish.
TABLES
TABLE S
KEY
S#
ROWS
S1
S2
S3
S4
S5
COLUMNS
SNAME
SMITH
JONES
BLAKE
CLARK
ADAMS
STATUS
20
10
30
20
30
CITY
LONDON
PARIS
PARIS
LONDON
ATHENS
VIEWS
TABLE S
VIEW
S#
STATUS
CITY
OR
VIEWS
OR A
Views
A VIEW is a named table that is represented, not by its own physically separate,
distinguishable stored data, but rather by its definition in terms of other named tables.
VIEWS are created for base tables or views or a combination of views and tables.
When you define a view DB2 stores the definition of the view in the DB2 catalog. Data is
physically present in base tables only and not in views. When a view is accessed then data is
dynamically retrieved from the base table.
Advantages Of Views
1. They provide a certain amount of logical data independence in restructuring the
database
2. They allow the same data to be seen by different users in different ways.
3. Automatic security is provided for data that is present in the base table by creating a
view in which sensitive data is not visible.
INDEX SPACES
INDEX SPACE 1
INDEX 1
INDEX
INDEX 1
RID
VALUE
PAGE P
Indexes
An index contains values from one or more of a tables columns and a pointer to the record
in a data which matches the index value. DB2 will find data more efficiently by scanning the
index and following the pointer than by scanning the entire tablespace.
Record ID of index has two parts. First part is to identify the page where the record lies
and the second part is the byte offset from the bottom of the page identifying the record.
Index is structured in ascending or descending sequence on one or more columns. A given
value of interest can be located quickly in the index because of their ascending or
descending structure.
An index created on a table in a partitioned table space is a partitioned index and is divided
into multiple index spaces.
Indexes are of two types, unique and non unique indexes. A non unique index can reference
duplicate values, a UNIQUE INDEX will not. You can create an index any time after you
create the table. But creating an index before loading the data provides significant
performance advantages.
Indexes can be clustered or non clustered. A clustering index is one in which the records are
physically stored in data pages in the sequential order of their index values. The index is
used to control physical placement of the indexed records. Newly inserted records are
physically stored such that the physical sequence of those records in storage closely
approximates the logical sequence as defined by the index. In a non clustered index the
records will not be in the order of index values.
A table can have any number of indexes but it can have only one clustered index.
Clustering is extremely important for optimization purpose. The optimizer will try to
choose an access path based on the clustering index .
For detailed explanation of indexes please refer More about indexes, chapter 12.
ALIASES
Aliases
Aliases are useful for creating meaningful names for TABLES and VIEWS. ALIASES are
created using CREATE ALIAS statement. One user can use an ALIAS created by another
user since aliases are not private to the creator
EXAMPLE
Suppose user ALPHA creates a table called SAMPLE.
CREATE TABLE SAMPLE
The fully qualified name of the table SAMPLE is ALPHA.SAMPLE and another user
BETA can refer to the table sample by its fully qualified name.
SELECT *
FROM ALPHA.SAMPLE
The user BETA can create an alias called ZTEST for the table ALPHA.SAMPLE using
create statement.
CREATE ALIAS ZTEST FOR ALPHA.SAMPLE
And now he can refer to the table SMPLE created by ALPHA by simply referring to the
alias ZTEST
SELECT *
FROM ZTEST
Another user GAMMA can also use BETAS ALIAS ZTEST to refer to ALPHAS
SAMPLE table.
SELECT * FROM
BETA.ZTEST
SYNONYMS
Synonyms
A SYNONYM like an ALIAS is an alternative name for a table. Creating a SYNONYM for
a table or view will allow the creator to refer to those tables and views by the more
meaningful synonym created by him.
EXAMPLE
Suppose user ALPHA creates a table called SAMPLE.
CREATE TABLE SAMPLE
The fully qualified name of the table SAMPLE is ALPHA.SAMPLE and another user
BETA can refer to the table sample by its fully qualified name.
SELECT *
FROM ALPHA.SAMPLE
The user BETA can create a SYNONYM called ZTEST for the table ALPHA.SAMPLE
using create statement.
CREATE SYNONYM ZTEST FOR ALPHA.SAMPLE
And now he can refer to the table SAMPLE created by ALPHA by simply referring to the
SYNONYM ZTEST
SELECT *
FROM ZTEST
However the user BETA and table ALPHA.SAMPLE must be at the same site. Also the
name ZTEST is completely private to the user BETA. Another user GAMMA cannot use
the synonym created by BETA and if it wants a synonym it should be created on
ALPHA.SAMPLE.
DB2 CATALOG
DB2
CONTAIN
SYSTEM .
CATALOG
WHEN A
TABLES
ARE
THE
THEY ARE
SYSIBM.SYSTABLES ,
SYSIBM.SYSCOLUMNS .
SYSIBM.SYSTABLESPACE ,
SYSIBM.SYSTABAUTH
DB2 Catalog
The CATALOG in DB2 is a system database that contains information concerning various
objects that are of interest to DB2 itself. Examples of such objects are tables, views,
indexes, databases, plans, packages, access privileges, and so on. These information is
essential, if the system is to able to do its job properly.
CATALOG itself contains TABLES and you can see the contents of catalog tables using
normal query language ( SQL ). When you create, drop or alter any structure, DB2 updates
or deletes rows of the catalog that describe the structure.
DBA s and application programmers may use catalog tables to determine
Which application plan and packages use which indexes
Which tablespaces, tables and indexes are in a database
An indexs structure, whether unique or clustered or the number of levels present in an
index
The amount of physical space used and remaining
Who created an object and who owns it.
Which plans and packages use objects in a database.
Who has authorization to create objects
Which plans and packages use which tables and tables and views
Which synonyms and aliases have been created on tables and views
Who is authorized to execute which plans and packages etc
Optimizer component of bind will use catalog information to choose best access strategy.
DB2 DIRECTORY
DB2
DIRECTORY
REQUIRED
CONTAINS INFORMATION
USES
THE
RBA
CONTAINS THE
BUFFER POOLS
Buffer Pools
Buffer pools, also known as virtual buffer pools, are areas of virtual storage used
temporarily to store pages of table spaces or indexes. When an application program needs
to access a row of a table, DB2 retrieves the page containing that row and places the page
in a buffer. If the row is changed, the buffer must be written back to the table space. If the
needed data is already in a buffer, the application program will not have to wait for it to be
retrieved from DASD. The result is faster performance.
DB2 can provide 2 types of buffer pools, 4K and 32K buffer pools. There are fifty 4K
buffer pools named BP0, BP1, P49 and ten 32K buffer pools named BP32K, BP32K1,
BP32K9. DB2 manages each buffer pools separately . Generally system administrator
decides how much memory to allocate for buffer pools. The more memory allocated to
buffer pool the more data it can hold and therefore the greater the likelihood that an
application request will find the data there.
4.
Data Types
This chapter describes various data types used in DB2 and their examples. COBOL
declarations of the corresponding DATA TYPES are also included.
The sub divisions of this chapter are
4.1.
Numeric Data
4.1.1. Nulls
4.2.
String Data
4.3.
Character Format
4.4.
Date/Time Data
4.5.
DATA TYPES
NUMERIC DATA
SMALLINT :
INTEGER
DECIMAL (P,Q):
FLOAT (M)
REAL
FLOAT (M)
FLOAT
RANGE OF VALUES
SMALLINT
-32768 to +32767
INTEGER
-2147483648 to +2147483647
DECIMAL (P ,Q)
MAXIMUM 31 DIGITS
0 < P < 32 AND ( 0 <= Q <= P )
REAL
FLOAT
5.4E-79 to 7.2E+75.
5.4E-79 to 7.2E+75.
DECIMAL(5, 2)
SMALLINT
INTEGER
NULLS
NULL
NOT NULL WITH DEFAULT
EXAMPLES
SPKZ
DRU
HDNR
DECIMAL(5, 2)
SMALLINT
INTEGER
NULL
NOT NULL
NOT NULL WITH DEFAULT
Nulls
Null values are used in a table when actual values are unknown. Suppose the weight of a
part in the SUPPLIER-PARTS DATABASE is null, then it means that
(1) The part exists
(2) It does have a weight
(3) We do not know what the value is
In other words we do not know a genuine weight value that can sensibly be put in the
weight slot in the row for the part in question. Instead we mark that slot as null and we
interpret that mark to mean precisely that we do not know what the real value is. we can
insert a null value in the WEIGHT column if it is declared as NULL. But if it is declared as
NOT NULL WITH DEFAULT, it is possible to insert a row into the table without
specifying a value for WEIGHT column. In that case the column will contain default values
corresponding to the column data type.
Suppose that NOT NULL is specified for column WEIGHT in the SUPPLIER-PARTS
DATABASE, then this will guarantee that every row in table P will always contain a
genuine (not null) WEIGHT value. In other words a value must always be provided for
column WEIGHT when a row is inserted into the P table.
If a given column is allowed to contain nulls and a row inserted into the table with no value
provided for that column DB2 will automatically place a null in that position. Suppose that
the WEIGHT column in supplier-table database is specified as NULL, then we can insert a
row in the table P without specifying a value for WEIGHT. DB2 will automatically put a
null value in that column.
NOT NULL WITH DEFAULT means the column in question cannot contain nulls but it is
nevertheless still legal to omit a value for the column on insert. If a row is inserted and no
value is provided for some column to which NOT NULL WITH DEFAULT applies DB2
automatically places one of the following non null default values in that position.
STRING DATA
CHARACTER FORMAT
RANGE OF VALUES
CHARACTER(n)
1 TO 254
VARCHAR(n)
LONG VARCHAR
CHAR (20)
VARCHAR (60)
LONG VARCHAR
GRAPHIC FORMAT
GRAPHIC(n) :
RANGE OF VALUES
GRAPHIC(N)
1 TO 127
VARGRAPHIC(N) :
LONG VARGRAPHIC:
GRAPHIC (10)
VARGRAPHIC (80)
LONG VARRRAPHIC
INTERNAL REPRESENTATIONS
DATE
YYYYMMDD
TIME
HHMMSS
TIMESTAMP
YYYYMMDDHHMMSSNNNNNN
DATE
TIME
TIMESTAMP
DATATYPE
CCTEMP SMALLINT
COBOL DECLARATION
CCTEMP INT
CCTEMP DECIMAL(9,3)
CCTEMP FLOAT(21)
01 CCTEMP COMP-1.
CCTEMP FLOAT(53)
01 CCTEMP COMP-2.
CCTEMP CHAR(10)
CCTEMP VARCHAR(80)
01 CCTEMP
49 VARLEN PIC S9(4) COMP.
49 CCVAR
PIC X(80).
5.
SQL Programming
IN DB2 operations are done using structured query language. This chapter explains types
of SQL and their usage. SQL statements are divided into
DDL Statements
DML Statements
Control Statements
SQL PROGRAMMING
SQL (STRUCTURED QUERY LANGUAGE ) IS
THE LANGUAGE USED TO ACCESS DATA
IN DB2 TABLES
SQL
DDL
DML
CONTROL
STATEMENTS
CREATE
ALTER
DROP
SELECT
UPDATE
INSERT
DELETE
CONTROL STATEMENTS
GRANT
REVOKE
COMMIT
ROLLBACK
5.1.
DDL Statements
Data definition language statements used for creating, changing and dropping DB2 objects.
The following sections explain these statements with suitable examples
5.1.1. Create Database
5.1.2. Create Table Space
5.1.3. Create Table
5.1.3.1.
Keys
5.1.3.2.
Primary Keys
5.1.3.3.
Foreign Keys
CREATE DATABASE
CREATE TABLESPACE
EXAMPLES
1.
2.
CREATE TABLE
EXAMPLES
1.
KEYS
SNAME
S1
S2
S3
SMITH
JONES
BLAKE
STATUS
20
10
30
CITY
LONDON
PARIS
PARIS
KEY
PRIMARY KEY
A PRIMARY KEY IS A UNIQUE KEY THAT IS A PART OF THE
DEFINITION OF A TABLE
P#
P1
P2
P3
P4
P5
P6
PNAME
NUT
BOLT
SCREW
SCREW
CAM
COG
COLOR
RED
GREEN
BLUE
RED
BLUE
RED
WEIGHT
12
17
17
14
12
19
CITY
LONDON
PARIS
ROME
LONDON
PARIS
LONDON
PRIMARY KEY
FOREIGN KEYS
TABLE SP
SNAME
STATUS
S1
S2
SMITH
JONES
20
10
..
PRIMARY KEY IN S
CITY
S#
LONDON
PARIS
S1
S1
S2
.
P#
QTY
P1
P2
P1
.
300
200
300
..
FOREIGN KEY IN SP
CREATE VIEW
SNAME
STATUS
CITY
VIEW : GOOD_SUPPLIERS
S#
STATUS CITY
CREATE INDEX
EXAMPLES
1.
2.
3.
ALTER TABLE
EXAMPLES
1.
2.
DROP
DROP
FREE
ALIAS
alias name
DATABASE database name
INDEX
index name
STOGROUP stogroup name
SYNONYM synonym name
TABLE
table name
TABLESPACE
table space name
VIEW view name
PACKAGE collection-id.package-id
PLAN
Drop
The results of dropping various objects are given below.
1. Dropping an alias has no effect on any view or synonym that was defined using the
alias.
2. When you drop the database , the database and all of its table spaces, tables, index
spaces, and indexes are dropped.
3. Whenever an index is directly or indirectly dropped ,its index space is also dropped.
4. When the synonym is dropped, view or alias that defined using the synonym are not
dropped.
5. Whenever a table is directly or indirectly dropped, all privileges on the table, all
referential constraints in which the table is a parent or dependent, and all synonyms,
views, and indexes defined on the table are also dropped.
6. Whenever a table space is directly or indirectly dropped, all tables in the table space are
also dropped.
7. Whenever a view is directly or indirectly dropped, all privileges on the view and all
synonyms and views that are defined on the view are also dropped.
8. when the package version is dropped, all privileges on the package are dropped and all
plans that are dependent on the execute privilege of the package are invalidated.
5.2.
DML Statements
Data manipulation statements are used for retrieving data from DB2 tables. The following
statements together known as data manipulation language.
5.2.1. Select
5.2.1.1.
Comparison Operators
5.2.1.2.
Select Distinct
5.2.1.3.
Multiple Conditions
5.2.1.4.
Order By
5.2.1.5.
In, Between
5.2.1.6.
Partial Search
5.2.1.7.
Aggregate Functions
5.2.1.8.
Group By
5.2.1.9.
Having
DML STATEMENTS
SELECT
SQL SELECT
REQUIRED SEQUENCE
SELECT
FROM
WHERE
ORDER BY
EXAMPLE
Q:
QUERY
SELECT S# , STATUS
-TELLS WHICH COLUMNS TO USE
FROM S
-TELLS WHICH TABLES TO USE
WHERE CITY = PARIS
-TELLS WHICH ROWS TO USE
ORDER BY STATUS DESC ;
-TELLS HOW TO SEQUENCE THE RESULT
RESULT
S#
STATUS
S3
S2
30
10
COMPARISON OPERATORS
EQUAL
^=
NOT EQUAL
<>
NOT EQUAL
>
GREATER THAN
^>
>=
<
LESS THAN
^<
<=
SELECT DISTINCT
QUERY
RESULT
P#
P1
P2
P3
P4
P5
P6
SELECT DISTINCT P#
FROM SP;
MULTIPLE CONDITIONS
AND
OR
Q1 :
Q2 :
QUERY 1 :
QUERY 2 :
RESULT 1
RESULT 2
S#
SNAME
S#
SNAME
S1
S4
SMITH
CLARK
S1
S2
S4
SMITH
JONES
CLARK
ORDER BY
RESULT
P#
P1
P5
P4
P2
P3
P6
WEIGHT IN GRAMS
WEIGHT IN GRAMS
WEIGHT IN GRAMS
WEIGHT IN GRAMS
WEIGHT IN GRAMS
WEIGHT IN GRAMS
=
=
=
=
=
=
5448
5448
6356
7718
7718
8448
IN, BETWEEN
IN
BETWEEN:
Q1
Q2
QUERY 1
QUERY 2
RESULT 1
P#
PNAME
P1
P2
P3
P5
NUT
BOLT
SCREW
CAM
RESULT 2
WEIGHT
12
17
17
12
P#
P2
P3
P6
PNAME
BOLT
SCREW
COG
17
17
19
WEIGHT
PARTIAL SEARCH
LIKE
LIKE
QUERY 1 :
QUERY 2 :
QUERY 3 :
QUERY 4 :
QUERY 5 :
NOT
RESULT 1
S#
SNAME
CITY
S1
S4
SMITH
CLARK
LONDON
LONDON
S#
SNAME
CITY
S2
S5
JONES
ADAMS
PARIS
ATHENS
RESULT 2
RESULT 3
S#
SNAME
S1
S4
SMITH
CLARK
CITY
LONDON
LONDON
RESULT 4
S#
SNAME
CITY
S1
S4
SMITH
CLARK
LONDON
LONDON
S#
SNAME
CITY
S3
S4
BLAKE
CLARK
PARIS
LONDON
RESULT 5
AGGREGATE FUNCTIONS
COUNT
SUM
AVG
MAX
MIN
Q1
Q2
QUERY 1
SELECT COUNT(*)
FROM S;
QUERY 2
(QTY)
RESULT 1
RESULT 2
1000
250
400
200
GROUP BY
QUERY
RESULT
P#
P1
P2
P3
P4
P5
P6
600
1000
400
500
500
100
HAVING
QUERY
RESULT
P#
P1
P2
P4
P5
SELECT P#
FROM SP
GROUP BY P#
HAVING COUNT (*) > 1.
JOINING TABLES
QUERY :
RESULT
S# SNAME STATUS S.CITY P#
S2
S2
S2
S3
S3
S3
JONES
JONES
JONES
BLAKE
BLAKE
BLAKE
10
10
10
30
30
30
PARIS
PARIS
PARIS
PARIS
PARIS
PARIS
P1
P4
P6
P1
P4
P6
RED
RED
RED
RED
RED
RED
12
14
19
12
14
19
LONDON
LONDON
LONDON
LONDON
LONDON
LONDON
SUB QUERIES
QUERY :
RESULT
SNAME
SMITH
JONES
BLAKE
CLARK
SELECT SNAME
FROM S
WHERE S# IN
( SELECT S#
FROM SP
WHERE P# = P2 ) ;
UNION
QUERY :
SELECT P#
FROM P
WHERE WEIGHT > 16
UNION
SELECT P#
FROM SP
WHERE S# = S2 ;
RESULT
P1
P2
P3
P6
INSERT
Q2 :
QUERY 1
INSERT
INTO P
VALUES ( P8, SPROCKET, PINK, 14, NICE ) ;
QUERY 2
INSERT
INTO P ( P#, CITY, WEIGHT )
VALUES ( P7, ATHENS, 24 );
P#
P8
P7
PNAME
.
SPROCKET
?
COLOR WEIGHT
CITY
PINK
?
.
NICE
ATHENS
....
14
24
RESULT 1
RESULT 2
UPDATE
QUERY
UPDATE P
SET COLOR = YELLOW ,
WEIGHT = WEIGHT + 5
CITY = NULL
WHERE P# = P1 ;
RESULT
P#
P1
PNAME
NUT
COLOR WEIGHT
CITY
YELLOW
17
?
DELETE
DELETE SUPPLIER S5
QUERY 1
DELETE
FROM S
WHERE S# = S5 ;
QUERY 2
DELETE
FROM SP
WHERE QTY > 300 ;
5.3.
Control Statements
Statements other than DDL and DML are explained in this section. They are
5.3.1. Grant
5.3.2. Revoke
5.3.3. Commit
5.3.4. Roll Back
CONTROL STATEMENTS
GRANT
TABLE PRIVILEGES
GRANT SELECT ON TABLE S TO CHARLY ;
GRANT SELECT , UPDATE (STATUS , CITY ) ON TABLE S
TO JUDY, JACK, JOHN ;
GRANT ALL PRIVILEGES ON TABLE S TO PUBLIC ;
COLLECTION PRIVILEGES
GRANT CREATE IN EWSK TO JOHN ;
DATABASE PRIVILEGES
GRANT CREATETAB ON DATABASE DBX TO NANCY ;
USE PRIVILEGES
GRANT USE OF TABLESPACE DBX.TS76 TO TOM ;
SYSTEM PRIVILEGES
REVOKE
EXAMPLES
REVOKE SELECT ON TABLE S FROM CHARLY ;
REVOKE UPDATE ON TABLE S FROM JOHN ;
REVOKE CREATETAB ON DATABASE DBX FROM NANCY ;
COMMIT
ROLLBACK
6.
Program Structure
This section gives an over view of a DB2 application program .Different sections to be
included in an application are explained briefly.
6.1.
Host Variables
Indicator Variables
6.3.
SQLCA
6.4.
6.5.
6.6.
SQLCA Warnings
6.7.
6.8.
Static SQL
6.9.
Dynamic SQL
PROGRAM STRUCTURE
STRUCTURE OF A PROGRAM THAT ACCESSES DB2
SQLCA
HOST VARIABLE DECLARATIONS
DECLARE TABLE STATEMENTS
DECLARE CURSOR
SQL STATEMENTS WITHOUT
FETCH
OPEN CURSOR
FETCH CURSOR
CLOSE CURSOR
Program Structure
Programs that access DB2 are written in a number of host languages - COBOL, PL/1, C ,
ASSEMBLER , FORTRAN, BASIC etc. These programs can contain SQL statements that
retrieves or updates database.
The start and end of SQL statements must be indicated by delimiters. The delimiters used in
COBOL are EXEC SQL and END-EXEC.
SQL statements must be coded with in these delimiters. Even if multiple SQL statements
appear sequentially, each SQL statement should be indicated by delimiters.
Pre compiler uses delimiters to identify SQL statements from the host language.
EXAMPLE OF USING DELIMITERS IN COBOL
EXEC SQL
UPDATE S
SET STATUS = 10
WHERE CITY = ATHENS
END-EXEC.
HOST VARIABLES
EXAMPLE(1)
SQL STATEMENT 1
INSERT INTO S
( S#, SNAME )
VALUES ( S6 , GEORGE )
SQL STATEMENT 2
INSERT INTO S
( S#, SNAME )
VALUES ( :SUPCODE, :SUPNAME )
In SQL statement 1 the values to be inserted are hard coded .Second SQL statement shows
the use of host variables in an embedded SQL .This statement could be included in a
processing loop with the programs logic assigning various values to the host variables.
EXAMPLE (2)
SQL STATEMENT
UPDATE S
SET STATUS = STATUS * :PERCENT
WHERE S# = :SUPCODE
In this example host variables are used to update a table .
(2)
EXEC SQL
INDICATOR VARIABLES
Indicator Variables
When the program is to receive a value from a column that allows nulls, the program can
get either a value or null. So the program requires two variables, a host variable to receive
value and an indicator variable to indicate the presence of null value in the selected column.
If DB2 attempts to indicate the presence of a null and the program does not provide an
indicator variable an error occurs.
If the value returned is null then the null indicator indicates that by a negative value and the
value in the host variable remains unchanged. The program should have an indicator
variable for each column that allows null.
In EXAMPLE1 when the selected column contains a null value then the program logic is
coded in such way to tackle it.
Example 2 shows that indicator variables are used for UPDATE operations also. Before
updating the table, the indicator variable is made negative and DB2 sets the column to null
ignoring the value in the host variable.
Indicator variable should be declared like you declare a host variable. Data type of an
indicator variable is SMALLINT and corresponding cobol declaration is given below
01 SUPNAMIND PIC S9(4) COMP.
Examples
1.
EXEC SQL
SELECT SNAME , CITY
INTO :SUPNAME:SUPNAMIND , :PGMCITY
FROM S
WHERE S# = S1
END EXEC.
IF SUPNAMIND < 0
PERFORM NONAME-SECTION
ELSE
PERFORM NAME-SECTION.
2.
IF ( some condition )
SUPNAMIND = -1
ELSE
SUPNAMIND = 0.
EXEC SQL
UPDATE S
SET SNAME = :SUPNAM:SUPNAMIND
WHERE S# = S1
END EXEC.
PROGRAM
STATUS OF EXECUTED SQL
SQLCA
SQL STATEMENTS
DB2
SQLCA
The SQL communication area (SQLCA) is a data structure that must be included in any
host language program using SQL .The SQLCA provides a way for DB2 to pass feedback
about its operations to the program .After executing an SQL DB2 returns via the
SQLCA ,codes indicating the execution was successful or identifying errors and special
conditions. The program can then test for these codes and react according to their content.
The SQLCA structure contains variables for a number of codes and messages.
Programmers can code the necessary structure(explained in next page) , copy it from a
source library or have DB2 generate it.
An include statement allows the source program to include SQLCA structure from the copy
library and is shown below.
EXEC SQL
INCLUDE SQLCA
END EXEC.
01 SQLCA.
05 SQLCAID
PIC X(8).
05 SQLCABC
PIC S9(9) COMP-4.
05 SQLCODE
PIC S9(9) COMP-4.
05 SQLERRM.
49 SQLERRML PIC S9(4) COMP-4.
49 SQLERRMC PIC X(70).
05 SQLERRPPIC X(8).
05 SQLERRD
OCCURS 6 TIMES
PIC S9(9) COMP-4.
05 SQLWARN.
10 SQLWARN0 PIC X.
10 SQLWARN1 PIC X.
10 SQLWARN2 PIC X.
10 SQLWARN3 PIC X.
10 SQLWARN4 PIC X.
10 SQLWARN5 PIC X.
10 SQLWARN6 PIC X.
10 SQLWARN7 PIC X.
05 SQLEXT.
10 SQLWARN8 PIC X.
10 SQLWARN9 PIC X.
10 SQLWARNA PIC X.
10 SQLSTATE PIC X(5).
CONDITION
STATUS
INTEGER
SQLCODE
ERROR
<0
WARNING
NOT FOUND
+100
SUCCESS
CHAR(1)
SQLWARN0
REQUEST
FAILED
OR W
SATISFIED
WITH SPECIAL
CONDITION
DATA NOT
FOUND
AND
SUCCESS
SQLCA WARNINGS
SQL WARNING
DESCRIPTION
SQLWARN0
SQLWARN1
SQLWARN2
SQLWARN3
SQLWARN4
SQLWARN5
SQLCA WARNINGS..
SQL WARNING
DESCRIPTION
SQLWARN6
SQLWARN7
SQLWARN8
SQLWARN9
SQLWARNA
-107
-117 THE NUMBER OF INSERT VALUES IS NOT THE SAME AS THE NUMBER
OF OBJECT COLUMNS
-119 A COLUMN IDENTIFIED IN A HAVING CLAUSE IS NOT INCLUDED IN
THE GROUP BY CLAUSE
-125 AN INTEGER IN THE ORDER BY CLAUSE DOES NOT IDENTIFY A
COLUMN OF THE RESULT
-150 THE OBJECT OF THE INSERT, DELETE, OR UPDATE STATEMENT IS A
VIEW FOR WHICH THE REQUESTED OPERATION IS NOT PERMITTED
-204
-205
-719
CODING AIDS
WHENEVER STATEMENT
EXEC SQL
WHENEVER Condition Action
END-EXEC
CONDITION:
SQLERROR
-- NEGATIVE SQLCODE
SQLWARNING
-- POSITIVE SQLCODE ( NOT +100 )
-- OR SQLWARN0 = W
NOT FOUND
-- SQLCODE = +100
ACTION:
GO TO :SECTA
-- CONTROL TRANSFERRED TO STATEMENT LABELED
SECTA
CONTINUE
-- PROGRAM CONTINUES WITH NEXT STATEMENT
-- USED TO CANCEL THE EFFECT OF PRIOR WHENEVER
Whenever Statement
WHENEVER statements help programmers to avoid checking SQLCODE after every SQL
statement. WHENEVER statements are SQL STATEMENTS that can be embedded in one
or more times in the host language program for branching to a paragraph depending on the
content of SQLCODE.
Each WHENEVER statement applies to all of the SQL statements that follow it in the
program listing, regardless of order in which the statements are actually executed. This
happens because COBOL precompiler puts appropriate branching instruction after every
SQL statement that follows the whenever statement.
WHENEVER statements can be used for three different conditions and these are similar to
IF THEN statements. IF SQLcode satisfies some condition then the program performs the
branching .
EXAMPLE
EXEC SQL
WHENEVER NOT FOUND CONTINUE
END-EXEC
EXEC SQL
WHENEVER SQLERROR PERFORM ERR-SECTION
END-EXEC
EXEC SQL
WHENEVER SQLWARNING PERFORM WARN-SECTION
END-EXEC
INCLUDE STATEMENT
SOURCE PROGRAM
EXEC SQL
PIC X(8).
PIC S9(9) COMP-4.
INCLUDE SQLCA
END-EXEC.
USING CURSORS
PROCESSING MULTIPLE ROWS
QUERY:
STATUS
2
10
20
CITY
LONDON
PARIS
LONDON
RANK
STATUS
CITY
20
10
20
LONDON
PARIS
LONDON
CITY
RANK
CITY
RANK
CITY
STATUS CITY
20
10
20
LONDON
PARIS
LONDON
DEFINE A CURSOR
EXEC SQL
DECLARE CURSOR K10 FOR
SELECT SNAME, CITY
FROM S
WHERE STATUS < 30
END-EXEC
DEFINITION
EXECUTION
EXEC SQL
DECLARE CURSOR K10 FOR
SELECT SNAME, CITY
FROM S
WHERE STATUS = :RANK
FOR UPDATE OF CITY
END-EXEC
EXEC SQL
OPEN K10
END-EXEC
EXEC SQL
FETCH K10 INTO :SUPNAME, :CITY
END-EXEC
EXEC SQL
UPDATE S
SET CITY = :NEWCITY
WHERE CURRENT OF K10
END-EXEC
EXEC SQL
CLOSE K10
END-EXEC
EXEC SQL
DECLARE CURSOR K10 FOR
SELECT SNAME, CITY
FROM S
WHERE STATUS = :RANK
FOR UPDATE OF CITY
END-EXEC
EXEC SQL
OPEN K10
END-EXEC
EXEC SQL
FETCH K10 INTO :SUPNAME, :CITY
END-EXEC
EXEC SQL
DELETE FROM S
WHERE CURRENT OF K10
END-EXEC
EXEC SQL
CLOSE K10
END-EXEC
STATIC SQL
PLAN
TO SELECT DATA
PROGRAM
PLAN
* SELECT
CALL
RESULT
SELECT
DB2
TABLE
STATEMENT
PROGRAMMER KNOWS THE SQL STATEMENT TO BE USED
AND ALWAYS DOES THE SAME FUNCTION ON THE SAME
TABLES AND COLUMNS.
BIND
AUTHORIZATION
HELD BY THE PLAN BINDER
DYNAMIC SQL
PLAN
PROGRAM
PLAN
PREPARE
DB2
EXECUTE
CALL
EXECUTE
TABLE
RESULT
PROGRAM HANDLES THE RESULT
STATEMENT
SQL STATEMENTS ARE PREPARED AT RUN TIME AND
EXECUTED. TARGET TABLE OR COLUMN CAN BE SPECIFIED
AT RUN TIME
BIND
ON SINGLE STATEMENT
AT STATEMENT EXECUTION
ACCESS STRATEGY NOT SAVED
AUTHORIZATION
.
EXEC SQL CLOSE CC END-EXEC
WORKING-STORAGE SECTION.
******************************************************************
*
*
* WORKING-STORAGE SECTION.
*
*
*
******************************************************************
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**
*
DB2-COMMUNICATION-AREA DECLARATIONS
*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*EXEC SQL INCLUDE SQLCA
END-EXEC.
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**
*
SQL-TABLE DECLARATIONEN
*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*EXEC SQL INCLUDE VT11018
( OUTPUT OF DCLGEN )
END-EXEC.
/
( WORKING STORAGE
VARIABLES )
LINKAGE SECTION.
******************************************************************
* L I N K AG E S E C T I O N
*
******************************************************************
*
.
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**
*
SQL-CURSOR DECLARATIONS
*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*EXEC SQL
DECLARE T11018_ALL_ROW CURSOR FOR
SELECT
TAB_INDEX
, DAHWV
, DAHWB
, DART
FROM
VT11018
ORDER BY TAB_INDEX
END-EXEC.
PROCEDURE DIVISION
******************************************************************
*
*
* PROCEDURE DIVISION
*
*
*
******************************************************************
*
******************************************************************
******************************************************************
*
.
.
/
******************************************************************
8100-OPEN-T11018-CURSOR SECTION.
******************************************************************
EXEC SQL
OPEN T11018_ALL_ROW
END-EXEC
******************************************************************
.
.
..
.
8100-CLOSE-T11018-CURSOR SECTION.
******************************************************************
EXEC SQL
CLOSE T11018_ALL_ROW
END-EXEC
STOP RUN.
7.
Program Preparation
This chapter explains the steps involved in executing a db2 application program.
Control information required for each step and examples are also provided
The topics discussed in this chapter are
7.1.
7.2.
7.3.
Precompile
7.4.
Bind
7.6.
7.7.
PROGRAM PREPARATION
STEPS IN PROGRAM PREPARATION
DCLGEN
PROGRAM PRE COMPILE
BIND
COMPILE AND LINK EDIT
EXECUTION
INPUT
OUTPUT
DECLARE TABLE
STATEMENT
CONTROL STATEMENTS
WHICH INCLUDE TABLE OR
VIEW NAME AND NAME OF
THE HOST LANGUAGE
DCLGEN
HOST LANGUAGE
DATA STRUCTURE
EXAMPLE
INPUT FOR DCLGEN
DCLGEN TABLE(S)
LIBRARY(NTCI.PTAB.DCL(S))
ACTION(REPLACE)
LANGUAGE(COBOL)
STRUCTURE(S)
QUOTE
OUT PUT FROM DCLGEN IN NTCI.PTAB.DCL(S)
******************************************************************
*
DCLGEN TABLE(S)
*
*
LIBRARY(NTCI.PTAB.DCL(S))
*
*
ACTION(REPLACE)
*
*
LANGUAGE(COBOL)
*
*
STRUCTURE(S)
*
*
QUOTE
*
*
IS THE DCLGEN COMMAND THAT MADE THE FOLLOWING
*
STATEMENTS
*
******************************************************************
EXEC SQL DECLARE S TABLE
(S#
CHAR(5) NOT NULL,
SNAME
CHAR(20),NOT NULL WITH DEFAULT
STATUS
SMALLINT NOT NULL WITH DEFAULT,
CITY
CHAR(15) NOT NULL WITH DEFAULT
) END-EXEC
******************************************************************
* COBOL DECLARATION FOR TABLE VT11010
*
******************************************************************
01
S.
10 S#
PIC X(5).
10 SNAME
PIC X(20).
10 STATUS
PIC S9(4) COMP.
10 CITY
PIC X(15).
******************************************************************
* THE NUMBER OF COLUMNS DESCRIBED BY THIS DECLARATION IS 4*
******************************************************************
PRECOMPILE
SOURCE MODULE
SOURCE LISTING
DIAGNOSTICS
CROSS REFERENCES
PRE COMPILE
MODIFIED
SOURCE CODE
(CONTAINS
CONSISTENCY
TOKEN)
DBRM
(CONTAINS
CONTOKEN )
Pre Compile
DB2 application programs include SQL statements and you cannot compile those programs
until you change the SQL statements into the language recognized by your compiler. Hence
you must use a pre compiler whose function is to analyze the host language source module,
stripping all SQL statements it finds and replacing them by host language call statements.
PRE COMPILER also creates a DBRM from the SQL statements it encountered. DBRM
communicates your SQL requests to DB2 during BIND process.
One DBRM is created for a program, the name of the DBRM and program will be the
same. DBRM contains SQL statements and host variable information extracted from the
source program. The DBRM also contains a consistency token that identifies the program
and ties the DBRM to the modified source statements by using the same consistency token
present in the modified source code.
The pre compiler does a syntax checking using the definition given by the DECLARE
TABLE statement on all SQL statements in the program. Pre compiler gives error ,
warnings and other diagnostic messages depending on the result of syntax checking .
BIND
OUTPUT
DBRM1
BIND
PLAN
DBRM2
DBRM1
BIND
PACKAGE1
BIND
DBRM2
BIND
PACKAGE2
PLAN
BIND
Bind
The out put of the precompiler contains extracted SQL statements from the source module.
But DB2 has to do the syntax checking and should determine the best access strategy for
each SQL. DB2 records all these information in the PACKAGE.
If a DBRM is thought of as an SQL source module then the package produced by binding
that DBRM can be thought of as the corresponding object module. In other words, a
package consists of a set of internal control structures , representing the compiled form of
the original SQL statements in the corresponding DBRM
Each package is assigned to exactly one collection when it is bound. When you bind a
package, you specify the collection to which the package belongs. The collection is not a
physical entity, and you do not create it; the collection name is merely a convenient way of
referring to a group of packages. Usually all of the packages used in a given application
would be assigned to the same collection
There are two types of bind. First method is to bind DBRMS to an application plan. In the
second method DBRMS are bound to the package and packages to the PLAN. Plan
contains pointers to the packages.
Bind examines the SQL statements in the input DBRM an checks whether all the necessary
elements of a statement are present and syntactically correct. It also checks that the
individual binding the plan is authorized to perform the operations requested by the SQL
statement.
Optimizer component of bind interrogates catalog tables, chooses the access path and
generates the machine code calls needed to execute the statement.
DBRM
CATALOG
PACKAGE BIND
LISTING
DIAGNOSTICS
PACKAGE
(EWSK)
(SXD11010)
(AM1240)
(SYSADMK )
(BIND)
(NO)
(CS)
(COMMIT)
(REPLACE)
When you BIND a package specify the collection to which the package belongs. The
collection is not a physical entity and you do not create it.
In the example collection name is EWSK and the package name produced by this bind is
EWSK.SXD11010
The owner of the package is AM1240.The owner of an object has all privileges on that
object. If no value is entered the default is the use of the primary AUTHID of the binder.
The qualifier parameter will be used as the qualifier of all unqualified tables and views
referenced in the application program.
Validate parameter is used to specify the method DB2 will use to validate the package or
plan. Validation can be performed during bind or when the program runs, indicated by the
choices of BIND or RUN with the VALIDATE parameter.
VALIDATE (RUN) is the default value.
EXPLAIN indicates whether to provide information to the user about the access strategy
decided by the bind. Default is EXPLAIN(NO)
ACTION parameter indicates whether the package is new or a replacement. ACTION
(ADD) will result in an error if the object already exists. The default value of REPLACE
will add the object or replace it if it already exists.
ISOLATION specifies the locking strategy while using cursors. Default is RR (repeatable
read) , can be over ridden using CS (cursor stability): For more information on
ISOLATION parameter please refer chapter 9
RELEASE parameter indicates when the locks should be released while using a cursor.
LIST OF PACKAGES
OR
DBRMS
OR
BOTH
PLAN BIND
LISTING
DIGNOSTIC
MESSAGES
PLAN
In the above example name of the plan is A610, two DBRMS, and three packages are
bound to the plan.
Parameters used in this example have the same meaning as in the bind package statement.
The parameter ACTION indicates whether a new package is to be added or replaced.
ACTION(REPL)RETAIN can be used only for BIND PLAN. RETAIN parameter
preserves EXECUTE privileges when you replace the plan. If RETAIN is specified then
those users who had been using the plan earlier will have the authority to use it after the
bind.
Determines the size (in bytes) of the authorization cache acquired in the EDM pool for the
plan. At run time, the authorization cache stores user IDs authorized to run. Consulting the
cache can avoid a catalog lookup for checking authorization to run the plan.
MODIFIED
SOURCE MODULE
(CONTAINS CONTOKEN)
COMPILER
OBJECT MODULE
LINK EDITOR
OTHER
OBJECT MODULES
LOAD MODULE
(CONTAINS CONTOKEN)
PRECOMPILER
DBRM
COMPILER
BIND
OBJECT
MODULE
PACKAGE
LINKAGE
EDITOR
LOAD
MODULE
OTHER
OBJECT
MODULES
LIST OF
PACKAGES
LOAD MODULE
PLAN / PACKAGES
MAIN MEMORY
BIND
APPLICATION
PLAN
CT
CT
PRE COMPILE
MODIFIED
SOURCE
DBRM
CT
CT
LOAD
MODULE
PLAN
CONTOKENS
SHOULD MATCH
TO EXECUTE
8.
Security Features
DB2 provides data integrity by using different security mechanisms. Data access is
controlled by using authorization IDs and privileges given to that ID. This chapter briefly
explains these security features and DB2s referential integrity support.
8.1.
Privileges
8.2.
Referential Integrity
SECURITY FEATURES
Security Features
Authorization IDS are provided to users of DB2 to prevent unauthorized use of DB2
objects. Users are known to DB2 by this authorization identifier given by the system
administrator and it is users responsibility to identify themselves to by supplying that ID
when they sign on to the system.
Two types of authorization IDs DB2 uses to control and track system utilization are
primary and secondary AUTHIDs.
Each individual is assigned a PRIMARY AUTHID that is used to sign on to the system.
Generally it is the primary authorization ID that identifies a process in DB2. When
unqualified tables, views, indexes are used in the application program, this AUTHID
becomes the qualifier of the object. The operations which can be performed by this
AUTHID depends on the privileges granted to it by system administrator or other users.
System administrator may provide a secondary authid to a group of developers who need a
set of privileges associated with that id. Now the user has all the privileges of both primary
and secondary authid. The secondary authorization ID is optional .
A user can use DB2 under either a primary AUTHID or secondary AUTHID or both.
Suppose you are using primary id and want to shift to secondary authid for some operation
to perform . This shift can be achieved by using the command
SET CURRENT SQLID = (name of secondary id).
PRIVILEGES
Privileges
SYSTEM ADMINISTRATOR has the authority on all objects in DB2. In order to
perform any operation in DB2, the user must hold appropriate privilege for the operation
and the object in question, Otherwise the request will be rejected. System administrator
grants single or group (bundled) privileges to users.
Group of privileges (BUNDLED PRIVILEGES) used in DB2 are shown below
SYSADM
SYSTEM ADMINISTRATOR AUTHORITY allows the holder to execute any operation
that the system supports.
SYSCTRL
SYSTEM CONTROL AUTHORITY allows the holder to execute any operation, except
for operation that access database contents.
Example: CREATE STOGROUP
DBADM
DATABASE ADMINISTRATOR AUTHORITY on a specific database allows the holder to
execute any operation that the system supports on the database
Example: SELECT, UPDATE etc
DBCTRL
DATABASE CONTROL AUTHORITY on a specific database allows the holder to execute
any operation that system supports except for data manipulation operation
Example: RECOVER DATABASE
DBMAINT
DATABASE MAINTENANCE AUTHORITY on a specific database allows the holder to
execute read only maintenance functions on the database
Example: DISPLAY DATABASE, START DATABASE etc
SYSOPR
SYSTEM OPERATOR AUTHORITY allows the holder to carry out console operator
functions on the system.
Example: STARTING AND STOPPING SYSTEM TRACE ACTIVITIES
PACKADM
package administrator authority on a specific collection allows the holder to create
packages in that collection and gives the holder all package privileges in that collection
REFERENTIAL INTEGRITY
DB2S REFERENTIAL INTEGRITY SUPPORT
INSERT RULE
UPDATE RULE
DELETE RULE
CASCADE
WILL SET THE CORRESPONDING FOREIGN KEY VALUES TO
NULL IF THE CONSTRAINT HAS BEEN SPECIFIED SET
NULL
TABLE SP
SNAME
SMITH
JONES
BLAKE
CLARK
ADAMS
STATUS
20
10
30
20
30
CITY
LONDON
PARIS
PARIS
LONDON
ATHENS
S#
S1
P#
S1 P1
S1 P2
S1 P3
S1 P4
P5
100
S1 P6
S2 P1
S2 P2
S3 P2
S4
P2
S4
P4
S4
P5
QTY
300
200
400
200
100
300
400
200
200
300
400
TABLE S
PRIMARY KEY ( S# )
In this example table S is the parent table and table SP is the dependent table. PFK and SFK
are constraint names that will be used by DB2 in diagnostic messages relating to the foreign
keys S# and P#. If the user does not specify the name DB2 will create one derived from the
name of the first column participating in the foreign key.
Four different cases of potential referential integrity violations for these tables are explained
below
CASE1
An insert on the SP table might introduce a shipment for which there is no matching
supplier. For example
INSERT
INTO SP (S#, P#, QTY )
VALUES ( S20, ) ;
CASE2
An update on column SP.S# of the SP table might introduce a shipment supplier number for
which there is no matching supplier. For example
UPDATE SP
SET S# = S20
WHERE.;
CASE3
A deletion on the S table might remove a supplier for which there exists a matching
shipment. For example
DELETE
FROM S
WHERE S# = S1 ;
CASE4
An update on column S.S# of the S table might remove a supplier for which there exists a
matching shipment . For example
UPDATE S
SET
S# = S20
WHERE S# = S1 ;
In order to enforce referential constraint, the system must deal with all four of these cases.
Explanation
CASE1
This situation is prevented by the virtue of the fact that SP.S# is a foreign key in table SP
matching the primary key S.S# of table S. Such an insert will simply be rejected. But an
insert that introduces a shipment for a supplier that does already exist in table S will be
accepted.
CASE2
In this case also the update will be rejected . But an update that introduces an SP.S# value
that does already exist in table S will be accepted.
CASE3
This situation is handled by the delete rule CASCADE. In general RESTRICT would mean
that the delete will be accepted only if there no such matching shipments. CASCADE
would mean that any such matching shipments will de removed anyway. And SET NULL
would mean that any such matching shipments will not be removed but will be updated so
that they are no longer matching.
CASE4
This situation is handled by the implicit update rule restrict, which means that the update
will be accepted only If no such matching shipments exist.
NEW POINT OF
CONSISTENCY
OLD
DATA UPDATES
UPDATED
DATA
UNIT OF RECOVERY
DATA
COMMIT
POINT OF
CONSISTENCY
NEW POINT OF
CONSISTENCY
ABNORMAL
TERMINATION
DATA UPDATES
OLD
OLD
DATA
DATA
Unit Of Recovery
A unit of recovery is the work done by a DB2 for an application, that changes DB2 data
from one point of consistency to another. A point of consistency is a time when all
recoverable data that an application program accesses is consistent with other data.
A unit of recovery begins with the first change to the data after the beginning of the job or
following the last point of consistency and ends at a later point of consistency. If failure
occurs within a unit of recovery, DB2 backs out any changes to data, returning the data to
its state at the start of the unit of recovery; that is, DB2 undoes the work.
DATA RECOVERY
BACKUP
DATA BASE
UPDATED
DATABASE
COMMIT
UPDATE1
UPDATE2
F
A
I
L
U
R
E
LOG
BACKUP
RECOVERED
DATABASE
RESTORE
UPDATE
LOG
Data Recovery
Backups are maintained by database administration for the data in DB2 subsystem.
Backups may be of the entire database or of one or more tablespaces. In case of failure
database recovery is done using these backups.
All data changes and other significant activities are recorded in logs by DB2. Database
manager may use the backup copies and the logs to re-establish the data base to the last
committed unit of work. Changes that were not committed before the failure are not
recovered in any case
In the given example, the backup is made for a database by DB2. After that the database is
changed , and that is made permanent by issuing a commit. Again the application program
tries to do another update and before its completion a failure occurs
Now we want to recover the data in the database. The database is recovered from he
backup and the changes that were made in that database till the last commit were done. and
the database is restored.
9.
Concurrency
Objects in DB2 can be used by many users at the same time. This is achieved by the using
proper locking system. This chapter explains how DB2 uses these locks and how much
control the programmer has over the concurrency in DB2.
9.1.
Concurrency
9.2.
Locking Strategy
9.3.
9.4.
9.5.
Isolation Parameter
CONCURRENCY
DB2 ALLOWS ANY NUMBER OF USERS TO ACCESS THE SAME TABLE AT
THE SAME TIME .THIS IS CALLED CONCURRENCY
DB2
CONCURRENCY
Concurrency
DB2 is a shared system, that is a system that allows any number of users to access the same
database at the same time. Any such system requires some kind of concurrency control
mechanism to ensure that concurrent transactions do not interfere with each other
operation. The absence of such a mechanism will lead to errors and inconsistencies in data
DB2 uses locks to control access to same database by multiple users. The basic idea of
locking is simple, when a transaction needs an assurance that some object that is interested
in, will not change in some unpredictable manner by another user. An exclusive lock on the
object will provide this assurance. The effect of the lock is to lock other transactions out of
the object, and thereby to prevent them from changing it. The first transaction is thus able
to carry out its processing in the certain knowledge that the object in question will remain
in a stable state for as long as the transaction wishes to.
If a transaction requests a lock that is not currently available, then the transaction simply
waits until it gets it. In practice the installation can specify a maximum wait time; If a
transaction ever reaches that threshold in waiting for a lock, it times out and the lock
request is failed.
LOCKING STRATEGY
Locking Strategy
DB2 allows multiple users to access same object at same time, but they are controlled by
locks. DB2 selects appropriate locking mechanism based on concurrency control
requirements inherent in the application program. They are called implicit locks.
In addition to the implicit locking mechanism, DB2 provides certain explicit facilities.
These explicit facilities are
1.
2.
3.
4.
Lock table statement can be coded in the application program to acquire an explicit lock on
an object on behalf of the application program. Other parameters are explained in the
following pages.
Example
LOCK TABLE SP IN EXCLUSIVE MODE;
LOCKSIZE PAGE
THIS MEANS THAT LOCKS ACQUIRED ON DATA IN THE TABLE
SPACE WILL BE AT TABLE LEVEL
LOCKSIZE ROW
THIS MEANS THAT THE LOCKS ACQUIRED ON DATA IN THE
TABLE SPACE WILL BE AT THE ROW LEVEL
LOCKSIZE ANY
THIS MEANS THAT DB2 WILL DECIDE THE APPROPRIATE
PHYSICAL UNIT OF LOCKING FOR THE TABLESPACE
ISOLATION PARAMETER
REPEATABLE READ(RR)
READ STABILITY(RS)
CURSOR STABILITY(CS)
UNCOMMITTED READ(UR)
Isolation parameter
If an SQL statement embedded in a host language program will return multiple rows, the
developer must declare in the program a cursor that presents them to the host program one
at a time, usually with in a repeatedly executed block. DB2 can handle locking for these
cursors using different ISOLATION levels.
ISOLATION(RR)
Repeatable read: A row or page lock is held for all accessed rows,
qualifying or not, at least until the next commit point. If the application process returns to
the same page and reads the same row again, the data cannot have changed and no new
rows can have been inserted.
ISOLATION (RS)
Read stability: A row or page lock is held for pages or rows that are
returned to an application at least until the next commit point. If a row or page is rejected
during stage 2 processing, its lock is still held, even though it is not returned to the
application.
If the application process returns to the same page and reads the same row again, the data
cannot have changed, although additional rows might have been inserted by another
application process. A similar situation can also occur if a row or page that is not returned
to the application is updated by another application process. If the row now satisfies the
search condition, it appears.
ISOLATION(CS)
Cursor stability: A row or page lock is held only long enough to
allow the cursor to move to another row or page. For data that satisfies the search
condition of the application, the lock is held until the application locks the next row or
page. For data that does not satisfy the search condition the lock is immediately released.
ISOLATION(UR)
Uncommitted read: The application acquires few locks and can run
concurrently with most other operations. But the application is in danger of reading data
that was changed by another operation but not yet committed.
10.
DB2I is an interactive facility available in DB2 . Almost all of the functions of DB2 are
available in DB2I , Which can be used by developers .This chapter contains
10.1. DB2I
10.2. SPUFI
DB2I
DB2 provides a number of commands for use in readying a program for execution that
programmers can use to perform the functions required to convert code from source to
executable modules. A convenient alternative is to work through DB2I , which provides a
menu interface to the necessary command processor . If you develop programs using TSO
and ISPF, you can prepare them to run using the DB2 Program Preparation panels. These
panels guide you step by step through the process of preparing your application to run.
There are other ways to prepare a program to run, but using DB2I is the easiest, as it leads
you automatically from task to task.
DB2I primary option menu lists the functions it can perform. The user can select any one of
these functions according to his requirements
SPUFI (SQL processor using file input) supports the online execution SQL statements from
a TSO terminal. SPUFI is intended basically for application programmers who wish to
perform SQL portions of their programs.
The DCLGEN menu allows users to invoke the declarations generator program, which
produces the DECLARE TABLE statements and host language data structure.
Other options like PRECOMPILE, BIND, RUN are used for preparing and executing DB2
application program.
UTILITIES menu helps the user to invoke DB2 online utilities like LOAD, REORG,
RECOVER etc. The necessary utility control statements to direct the operation of the
specific utility must be created before the utility is invoked.
SPUFI
INPUT SQL
STATEMENTS
SPUFI
OUTPUT
RESULTS
DB2
11.
Utilities
For analyzing and managing physical data present in data base, DB2 offers a number of
utilities . This chapter gives a brief explanation of these utilities
11.1.
Load
11.2.
Runstats
11.3.
Reorg
UTILITIES
ONLINE UTILITIES
LOAD
REORG
RECOVER
RUNSTATS
IMPORTANT STAND ALONE UTILITIES ARE
DSNJU003
DSNJU004
DSN1CHKR
LOAD
INPUT
DATA
LOAD UTILITY
EXAMPLE
CONTROL INFORMATION FOR LOAD UTILITY
LOAD DATA
RESUME NO
LOG NO
inddn ddname
INTO TABLE D2110K.S
( S# POSITION (1)
P# POSITION (6:11)
QTY POSITION (12:15)
CHAR 5
CHAR 6
INTEGER );
Load
Load utility is used to load data from a sequential file to a TABLE in a table space.
In the previous example the TABLE S is loaded from the dataset specified in the load jcl.
ddname of the input dataset that is used in the LOAD JCL is given in INDDN parameter.
Each fields and their positions are also specified.
If the table space already contains data, you can choose whether you want to add new data
to existing data or replace the existing data. This can be done using the parameter
RESUME.
There are three options for RESUME.
RESUME NO: Indicates that the dataset is to be empty. This is the default option.
RESUME NO REPLACE: This causes the utility to over write the existing data.
RESUME YES: This allows the utility to add new rows to the existing table.
The LOG NO command instructs the utility not to record data in the log as they are
loaded .IF the user does not specify LOG NO , the utility records the changes which can be
used for recovery purpose. Default is LOG YES. Recording data in the log during a load
can increase the time required for the load significantly.
RUNSTATS
EXAMPLE
CONTROL INFORMATION FOR RUNSTATS UTILITY
RUNSTATS TABLESPACE D2110K.TABSP
TABLE(ALL)
INDEX(ALL) ;
Runstats
The RUNSTATS utility reads tablespaces and indexes to collect statistics describing the
data. The main statistics collected include number of rows in the table, number of pages
that contain the rows of the table, number of distinct values of indexed column , percentage
of space occupied by rows etc. RUNSTATS utility uses this information to update
CATALOG tables.
In the previous example RUNSTATS utility is used for table space TABSP in database
D2110K. All tables in the tablespace are specified by TABLE(ALL) keyword. Here you can
specify the table name in parentheses after keyword TABLE on which the utility has to run.
You can obtain statistics on all indexes on all tables in the named table space by specifying
INDEX(ALL).The user can get statistics of one more specific indexes by specifying them in
parentheses after the keyword INDEX .
The RUNSTATS utility is useful for finding out the free space remaining in a tablespace and
we use that information for reorganizing the tablespace.
REORG
REORG UTILITY IS USED TO REORGANIZE DATA ON
PHYSICAL STORAGE OF TABLES. DIFFERENT PHASES
OF REORG UTILITY ARE
UNLOADS ROWS FROM A TABLE SPACE
RELOADS ROWS IN A NEATER ARRANGEMENT
WITH FREE SPACE
REBUILDS INDEXES
DOES NOT VALIDATE DATA
Reorg
The REORG online utility reorganizes a table space or index to improve access
performance and reclaim fragmented space. In addition, the utility can reorganize a single
partition of either a partitioned index or a partitioned table space.
REORG utility reorganizes table space or index as you specify in control statements. When
an index space only is reorganized then the data pages are not processed. Only leaf pages
which contains indexes are scanned.
Proper scheduling of reorganizations significantly improves performance of all application
programs.
In the given example REORG utility is run on tablespace TABSP in database D2110K. If
you want to reorganize an index then specify REORG INDEX (index name) . LOG NO
parameter is specified in the example to avoid writing data records in the log while loading
the tablespace.
12.
Advanced DB2
This section explains some of the advanced concepts in DB2. The detailed discussions on
indexes and DB2 locks are included. Advanced topics present in this section are
12.1. More About Indexes
12.1.1. Example Of An Index
12.1.2. Clustered Indexes
12.1.3. Non Clustered Indexes
12.2. Special Registers
12.3. More About Locks
12.3.1. Modes Of Table And Tablespace Locks
12.3.2. Modes Of Row And Page Locking
12.3.3. Lock Mode Compatibility Of Table And Table Space Locks
12.3.4. Lockmode Compatibility Of Row And Page Locks
12.4. Invoking Online Utilities
EXAMPLE OF AN INDEX
25
17
25
61
33
86
40
ROOT PAGE
61
70
75
86 INTERMEDIATE
PAGES
LEAF
PAGES
. . 17
. . 25
. . 33
40
. 61
. . 70
. . 75 . . 86
DATA
PAGES
Example Of An Index
Indexes in DB2 are based on a structure known as B-Tree. Indexes can have more than one
level of pages. Index pages that point directly to the data in the tables are called leaf pages.
If the index has more than one leaf page, it must have at least one non leaf page, containing
entries that point to leaf pages. If it has more than one non leaf page, the non leaf pages
whose entries point directly to leaf pages are said to be on the first level; there must be a
second level of non leaf pages to point to the first, and so on. The highest level contains a
single page, called the root page.
A typical index is shown in the figure, which is a multilevel, tree structured index with the
property that the tree is always balanced, that is that is all leaf entries in the structure are
equidistant from the root of the tree. and this property is maintained as new entries are
inserted into the tree and existing entries are deleted
The root page is the top of the structure. The root page will contain an entry for each non
leaf or immediate page. The entry in the root page consists of the high value contained on
the intermediate page and a pointer to that page.
The immediate pages are similar in structure to the root page, expect that the range of
values addressed is more specific. The immediate page contains an entry for each of the leaf
pages addressed. The entry consists of the high value contained on the leaf page and a
pointer to this leaf page.
The leaf pages contain the RID, using which the record can be located in a table space. The
leaf pages collectively address the entire table.
CLUSTERED INDEXES
25
17
61
ROOT PAGE
33
40
INTERMEDIATE
PAGES
LEAF
PAGES
DATA
PAGES
Clustered Index
A clustering index is one for which the sequence defined by the index is the same as or
close to the physical sequence. The clustering holds the most potential for performance
gains. With a clustering index DB2 takes responsibility for maintaining rows in sequence on
the clustering index columns as long as there is free space. DB2 maintains clustering by
placing inserted rows in the indexed columns sequence on available free space in the data
pages.DB2 can then process the table in that order efficiently. If it is a non clustering index
then DB2 has to reread data pages to identify all the qualifying rows, which will reduce
performance.
Clustering is valuable when DB2 must process a columns values in sequence. The SQL
statements ORDER BY, GROUP BY, and DISTINCT require such processing. If a column
specified in these operation and there is not a suitable index on the column, DB2 must sort
it to put it in sequence before returning even one row to the user. If there is a clustering
index on that column DB2 uses this column to retrieve the rows in sequence and return the
rows immediately one by one.
To specify a clustering index, use the CLUSTER clause in the CREATE INDEX statement.
CREATE INDEX STATEMENT FOR A CLUSTERED INDEX
CREATE UNIQUE INDEX D2110N.I11010U1
ON D2110N.T11010
(TAB_INDEX)
BUFFERPOOL BP0
USING STOGROUP SGDB2O
PCTFREE 20
FREEPAGE 10
PRIQTY 40
SECQTY 20
CLOSE NO
CLUSTER;
25
17
61
ROOT PAGE
33
40
INTERMEDIATE
PAGES
LEAF
PAGES
DATA
PAGES
SPECIAL REGISTERS
CURRENT DATE
CURRENT DEGREE
CURRENT PACKAGESET
CURRENT RULES
CURRENT SERVER
CURRENT SQLID
CURRENT TIME
CURRENT TIMESTAMP
CURRENT TIMEZONE
USER
Special Registers
DB2 supports a number of special registers. A special register is a storage area that DB2
defines for a process. Wherever its name appears in an SQL statement, the name is replaced
by the register's value when the statement is executed. Thus, the name acts like a function
that has no arguments. (zero argument built in scalar functions)
You can use the SET statement to change the current value of a register. Where the
register's name appears in other SQL statements, the current value of the register replaces
the name when the statement executes. A commit or rollback operation has no effect on the
values of special registers. Nor does any SQL statement, other than SET statement can
change a register value
CURRENT DATE, specifies the current date. The data type is DATE. The date is derived
by the DB2 that executes the SQL statement that refers to the special register.
Example: Display the average age of employees.
SELECT AVG(YEAR(CURRENT DATE - BIRTHDATE))
FROM DSN8410.EMP;
CURRENT PACKAGESET specifies a string of blanks or the collection ID of the package
or packages that will be used to execute SQL statements. The data type is CHAR(18).
EXAMPLE
Example: For executing a program, identify the collection ID for its package as EWSA.
SET CURRENT PACKAGESET = 'EWSA';
CURRENT SQLID specifies the SQL authorization ID of the process. The data type is
CHAR(8). This SET statement is used to change the authorization id for a process
Example: Set the SQL authorization ID to 'GROUP34' (one of the authorization IDs of the
process).
SET CURRENT SQLID = 'GROUP34';
CURRENT TIME, specifies the current time. The time is derived by the DB2 that executes
the SQL statement that refers to the special register. ,
Example: Display information about all project activities and include the current date and
time in each row of the result.
SELECT DSN8410.PROJACT.*, CURRENT DATE, CURRENT TIME
FROM DSN8410.PROJACT;
CURRENT TIMESTAMP, specifies the current timestamp. The data type is TIMESTAMP.
The timestamp is derived by the DB2 that executes the SQL statement that refers to the
special register.
Example: Display information about the full image copies that were taken
in the last week.
SELECT * FROM SYSIBM.SYSCOPY
WHERE TIMESTAMP > CURRENT TIMESTAMP - 7 DAYS;
CURRENT USER specifies the primary authorization ID of the process. The data type is
CHAR(8).
Example: Display information about tables, views, and aliases that are owned by the
primary authorization ID of the process.
SELECT * FROM SYSIBM.SYSTABLES WHERE CREATOR = USER;
IS
INTENT SHARE
IX
INTENT EXCLUSIVE
SHARE
UPDATE
SIX
EXCLUSIVE
IS :
S
IX :
SIX:
THE LOCK OWNER CAN READ ANY DATA IN THE TABLE AND
CHANGE ROWS IN THE TABLE PROVIDED IT CAN OBTAIN AN
X LOCK ON THE TARGET ROW OR PAGE FOR CHANGE. ROW
LOCKS ARE NOT OBTAINED FOR READING.
S :
THE LOCK OWNER CAN READ ANY DATA IN THE TABLE AND
WILL NOT OBTAIN ROW OR TABLE LOCKS
U :
THE LOCK OWNER CAN READ ANY DATA IN THE TABLE AND
MAY CHANGE DATA IF AN X LOCK ON THE TABLE CAN BE
OBTAINED. NO ROW OR PAGE LOCKS ARE OBTAINED
X :
MINIMUM SUPPORTING
TABLE/TABLE SPACE LOCK
SHARE
IS
UPDATE
IX
EXCLUSIVE
IX
S :
U :
X :
MODE OF LOCK B
IS
IX
SIX
IS
YES
YES
YES
YES
YES
NO
YES
YES
NO
NO
YES
NO
IX
YES
NO
YES
NO
NO
NO
SIXYES
NO
NO
YES
YES
NO
NO
NO
NO
NO
NO
NO
NO
NO
NO
NO
NO
NO
MODE OF LOCK B
S
YES YES
NO
YES NO
NO
NO
NO
NO
//*
DB2 LOAD
//*
//*=============================================================
//*
//*------------------------------------------------------------------*/
//*
T00101
//* -------------------------------------------------------------------/*
//T00101R EXEC DSNUPROC,PARM='DB2O,I650001T001012'
//DSNUPROC.SYSIN DD *
RUNSTATS TABLESPACE D20015.S001501
TABLE (ALL) INDEX (ALL)
/*
//*