DB2 Application Programming'
DB2 Application Programming'
DB2
Course Objectives
Research : System R
IMS/DB DB2
MVS
IMS Databases DB2 Databases
Course Plan
An overview
Relational Model
Relational Data Structure
Table
Relational Data Integrity
Entity Integrity
Referential Integrity
Relational Data Manipulation
Relational Algebra
Relational Data Structure.
Attribute
Column Value
- Not Applicable
- Not Available
Emp Name Project Join_Date
2000 Vijay GE 01/01/85
3000 Gupta ? 01/01/96
4000 Sridevi HP 01/02/95
Relational Data Integrity
Primary Key
- Uniqueness
- Minimality
Alternate Key
Foreign Key
Foreign Key
Department
Dept Name Location
101 Marketing Chennai
102 Personnel Mumbai
103 Admin Chennai
104 Training Chennai
Entity integrity
No column in the primary key can have a NULL value
Referential Integrity
Every foreign key value must either match a primary key
value of its associated parent table or it must be wholly
NULL .
Relational Algebra
Restrict Project Join Divide
Union Intersection Difference Product
Properties
They operate on all entire table; they donot operate on
individual rows of the table.
When the relational operator is applied to on or more
tables, the operation results in another table
RESTRICT
Emp # Join_Date
4000 01/02/95
JOIN
a1 b1
a2 b1
a1 b1 c1
a3 b2
JOIN a2 b2 c2
b1 c1 a3 b3 c3
b2 c2
b3 c3
INNER JOIN
Join on Dept#
Join on Dept #
Join on Dept #
Emp# Name Dept# Join_Date Name Location
2000 Vijay 101 01/01/85 Marketing Chennai
3000 Gupta 102 01/01/96 Personnel Mumbai
? ? 104 ? Training Madras
Full Outer JOIN
Emp# Name Dept Join_Date
2000 Vijay 101 01/01/85
3000 Gupta 102 01/01/96
4000 Sridevi 103 01/02/95
Join on Dept #
x
a x
y
a y
a z Divide
b x
a
c y
UNION
Emp # Name
3000 Gupta
UNION 2500 Singh
5000 Hari
2500 Singh
6000 Guru
3000 Gupta
5000 Hari
6000 Guru
INTERSECTION
Project 1
Emp # Name
2000 Patel
3000 Gupta
INTERSECTION
Project 2
Emp # Name
2500 Singh
Emp # Name
3000 Gupta
3000 Gupta
5000 Hari
6000 Guru
DIFFERENCE
Project1
Emp # Name
2000 Patel
3000 Gupta
Project 2 Difference
Emp # Name
2500 Singh
Emp # Name
3000 Gupta
2000 Patel
5000 Hari
6000 Guru
CARTESIAN PRODUCT
a x
a
a y
b
b x
c b y
PRODUCT
c x
x
c y
y
Relational Model : Some Advantages
* Easy to Understand
* Elimination of need to preplan “ HOW “ to get to
data
* Flexibility
Data Management in DB2
An Introduction
DB2 Data Objects
Storage Group
Databases
Tablespaces
Indexes
Bufferpools
EDM pool
BSDS
Logs
DB2 Tablespaces
FOOTER
Simple Tablespaces
101 1 101
104
102 3
102
103 4 103
104 2
Position
KEY
Indexes : Terminology
8 17 33 40
138 9 11 17 19 21 25 28 31 33 35 38 40 46 51 55
Leaf NodesPointing
to Data Pages
Clustering Index
25
8 17 33 40
138 9 11 17 19 21 25 28 31 33 35 38 40 46 51 55
Data
Pages
Non-clustered Index Scan
Stogroup
Database
Bufferpools
DB2 System Objects
• Bufferpool
• EDM Pool ( Environment Descriptor
Manager )
• BSDS ( Bootstrap Dataset )
• Logs ( Active and Archive logs )
Data Types : String
Data Types : Datetime
Datetime
Numeric
End Transaciton
SQL Command
All Changes“UNDONE”
SQL Command
COMMIT
ROLLBACK
Transactions : An example
Account 1 Account 2
Balance = 2000 Balance = 5000
Transaction
Account 1 Account 2
Balance = 1000 Balance = 6000
Transaction : ACID Properties
ATOMICITY
CONSISTENCY
ISOLATION
DURABILITY
Lost Update Problem
User 1
Quantity = 2000 User 2
Quantity = 2000
Uncommited Read
User 1
Quantity = 2000 User 2
Quantity = 2000
Incorrect Summary Problem
Locking
Attributes of locks
Object : How much data is marked “in-use”
Duration : How long is the lock is needed
Mode : How severe is the lock
Lock : Object
PAGE or ROW
Great concurrency
More locking overhead
TABLE or TABLESPACE
– ACQUIRE/RELEASE
– ISOLATION LEVEL
Lock : Mode
* Hardware Failure
* Program Failure
* Natural Calamity
Backing up data
* IMAGE COPY
* FULL
* INCREMENTAL
* MERGECOPY
* FUZZYCOPY
System Log
* RECOVER Utility
Tablespace is the unit of recovery
* Disaster Recovery
Integrity Enforcement
• Outside Db2
- RACF
• Within DB2
- Privileges
- Administrative Authorities
Application Programming Interface
SQL
• LOAD
• UNLOAD
• REORGF
• RUNSTATS
SQL - DDL
DATA
DEFINITION
LANGUAGE
SQL – Structured Query Language
SQL
• Storage Group
• Database
• Tablespace
• Table
• Index
• View
• Synonym
DDL - Opertions
Storage Group X X X
Database X X
Tablespace X X X
Table X X X
Index X X X
Synonym X X
View X X
DDL – System Naming Rules
DDL – CREATE Storage Group
Syntax:
CREATESTOGROUP stogroup-name
VOLUMES (vo11, vo12,…)
VCAT catalog – name
(PASSWORD password)
DB2 Application Programming
•COBOL
•PL/1
•C
•Assembler
•FORTRAN
Embedded SQL
Statement:
Coded in program,always does the same function on the same tables
and columns
Bind: on all SQL statements
Before program execution
Builds a stored Plan/Package
SQL Delimiters in COBOL
EXEC SQL
SQL statement
END –EXEC
•The EXEC and SQL keywords must appearon one line, but the remainder of the statement can
appear on subsequent lines
*The EXEC SQL must notbe coded before column 12
•COBOL comments are allowed any where within the delimiters
INCLUDE
EXEC
INCLUDE SQLCA/ SQLCA member-name
END-EXEC
Member-name
Member of the partitioned data set
The member can contain any COBOL variable declarations, source statements and any SQL
statements other than an INCLUDE statement.
DDL – ALTER Storage Group
Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES ( vo14, vo15, …)
REMOVE VOLUMES (vo11, vo12, . . . )
ALTER STOGROUP TRG1TO1
ADD VOLUMES (DBPK03)
REMOVE VOLUMES (DBPK01)
DDL – CREATE Database
Syntax:
CREATE DATABASE database – name
(STOGROUP stogroup – name)
(BUFFERPOOL bufferpool – name)
ERASE:
* Indicates whether the DB2 defined datasets are to be erased when tablespace
is dropped
LOCKSIZE
BUFFERPOOL:
CLOSE:
* Indicates whether data sets associated with tablespace;should be closed when there are no
current users of tablspace
* Default is YES
DDL – CREATE TABLESPACE Parameters
FREEPAGE:
* Specified number of pages after which
a completely empty page is available
* Default is FREEPAGE 0
PCTFREE:
* Specifies percentage of each page
available for future inserts
* Default is PCTFREE 5
DDL – CREATE TABLESPACE
Example:
CREATE TABLESPACE
IN DSN8DP2AP
USING STOGROUP DSNS62600
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BPO
DDL – ALTER TABLESPACE
Syntax : (Format 1)
CREATE TABLE tablename
(column-definition (, column-definition) . . .
(, primary-key-definition)
(, foreign-key-definition
(, foreign-key-definition) . . .
(other-parameters) )
( IN databasename.tablespacename/
IN DATABASE databasename)
DDL- CREATE TABLE
Syntax : (Format 2)
COLUMN- definition
colname coltype (NOT NULL/ NULL / NOT NULL WITH DEFAULT)
Primary-key definition:
PRIMARY KEY(colname1,colname2,…)
DDL- CREATE TABLE
foreign-key definition:
FOREIGN KEY (constraint-name)
(colname1(, colname2) . . .)
REFERENCES base-table
(ON DELETE RESTRICT/CASCADE/SET
NULL)
DDL-CREATE TABLE
Other parameters:
Example
Syntax:
ALTER TABLE tablename
ADD column-definition
VALIDPROC program-name NULL
primary-key-definition
referential-constrains
CRC? PRIMARY KEY
CRC? FOREIGN KEY constraint - name
DDL – CREATE INDEX
Syntax:
CREATE (UNIQUE) INDEX indexname
ON tablename (colname (ASC/DESC),…)
( USING STOGROUP stogroupname)
PRIQTY qty
SECQTY qty
ERASE YES/NO)
(CLUSTER) (SUBPAGES amount)
(BUFFERPOOL BPO/BP1/BP2)
(CLOSE YES/NO) (DSETPASS password)
(PCTFREE amount) ( FREEPAGE amount)
DDL- CREATE INDEX
Example:
CREATE UNIQUE INDEX XS
ON SUPPLIER (S#)
USING STOGROUP TRG1TO1
PRIQTY 16
SECQTY 4
ERASE NO
DDL – ALTER INDEX
Syntax :
ALTER INDEX index-name
BUFFERPOOL BPO/BP1/BP2
CLOSE YES/NO
DSETPASS password
FREEPAGE qty PCTFREE qty
USING STOGROUP stogroupname
PRIQTY amountSECQTY amount
ERASE YES/NO
DDL – CREATE VIEW
Syntax:
CREATE VIEW view-name
(column-name, . . .)
As subselect
WITH CHECK OPTION
DDL – CREATE SYNONYM
Syntax :
create synonym SYNONYM
FOR auth-id.table-name
DDL – DROP Statement
Syntax:
DROP object-type objectname
Example
DROP DATABASE TRG1TO1
DROP TABLE SUPPLIER
DROP INDEX XS
DDL- DROP Dependencies
DROP DEPENDENCIES
SQL- DML
DATA
MANIPULATION
LANGUAGE
DB2-DML-1
DML Overview
ko m m
ko ko ko
m k
ko m
o
DML – SELECT Statement
Syntax:
SELECT (all) DISTINCT) scalar-expression
FROM table(s)
(WHERE search-condition)
(GROUP BY column(s) )
(HAVING search-condition)
(ORDER BY column(s))
DML – SELECT Statement
Scalar Expressions
(LENGTH (SNAME) –1*2
SALARY+COMMISSION+BONUS
Search Condition
(SUBSTR (SNAME,1,3) = ‘VIJ’
AND
CITY = ‘MADRAS’
DML- SELECT Statement
•SELECT *
FROM SUPPLIER
•SELECT P#, ‘Weight in grams = ‘, WEIGHT * 454
FROM PARTS
DML – SELECT Statement
FROM PARTS
WHERE WEIGHT NOT BETWEEN 16 AND 19
DML – SELECT Statement
•Simple Subquery
•SELECT SNAME FROM SUPPLIER WHERE S# IN (SELECT S# FROM
SHIPMENT WHERE P# = ‘P2’)
DML – SELECT Statement
UNION
Union operation on union-compatible sets of rows
Labeled Duration:
•N units
Special Registers:
•CURRENT TIMEZONE
•CURRENT DATE
•CURRENT TIME
•CURRENT TIMESTAMP
DML – DATE / TIME Arithmetic
Examples:
•DATE(‘8/17/1996’) – DATE(’10/28/1996’)
•START_DATE + 1 YEAR + 6 MONTS
•CURRENT TIMESTAMP + 1 SECOND
•START_TIME – END_TIME < 080000
DML – INSERT Statement
Syntax:
INSERT INTO table[ (column [, column] …)]
Values (literal [,literal]….)
Or
INSERT INTO table [ (column[, column] …)]
subquery
DML – INSERT Statement
Examples
Syntax:
UPDATE table
SET column = scalar-expression [, column = scalar-expression]
[WHERE search-condition]
DML – UPDATE Statement
Single Row Update
UPDATE PARTS
SET COLOR =‘YELLOW’
WEIGHT = WEIGHT – 5
CITY = NULL
WHERE P# = ‘P2’
Syntax:
DELETE FROM table [WHERE condition]
•All COBOL host variables must be explicitly declared in the DATA DIVISION.
• A colon ( : ) must precede all host variables in an SQL statement
• The names of the host variables must be unique within the program. Host
variable names can be qualified with a structure name to make them unique
• Host variables, other than indicator variables, cannot be defined as arrays.
An OCCURS clause must only be specified when defining an indicator
structure.
SQL and COBOL Data types
PERFORM OPEN-PARA
PERFORM FETCH-PARA.
EXEC SQL
DECLARE cursor-name CURSOR WITH HOLD FOR
SELECT column-name-list
FROM table-name
WHERE search-condition
FOR UPDATE OF column-name
END-EXEC
WHENEVER
EXEC SQL
WHENEVER condition action
END-EXEC
condition : SQLWARNING
SQLERROR
NOT FOUND
action : CONTINUE
GOTO or GO TO procedure/section
Dynamic SQL
Statement:
Acquired during execution,and function can
vary and can be done to different tables and
columns
Bind: One single statement
At statement execution
Access strategy not saved..
Static SQL vs. Dynamic SQL
Statement:
Static : Object and Action known
Dynamic : Object or Action not known
Bind:
Static : is bound once
Dynamic : is bound every time.
Coding Dynamic SQL
OWNER
OWNER Vs CREATOR : Part II
If the qualifier is not specified, for STATIC DDL, the ID named in the
QUALIFER parameter at the time of BIND is the OWNER. If no qualifier
is supplied, the owner of the plan/package is the OWNER of the object
Qualified Objects : TABLE
» CHECK
» COPY
» DSN1COPY
» LOAD
» MERGECOPY
» MODIFY
» QUIESCE
» RECOVER
» REORG
» REPAIR
» RUNSTATS
» STOSPACE
LOAD Utility
Input:
LOAD DATA statement describing the data to be loaded
File containing data
Output
Loaded table or partition
Discard file of rejected records
Summary reports of errors encountered
LOAD Utility
Features
Automatic data conversion between compatible
data types
Data loaded in the sequence presented; no sort
invoked
Indexes built; duplicates checked
LOAD Utility
Phase Flow:
UTILINIT
RELOAD
SORT
BUILD
INDEXVAL
ENFORCE
DISCARD
REPORT
LOAD Utility
Example:
LOAD DATA INDDN(SYSREC)
RESUME YES
ENFORCE CONSTRAINTS
INTO TABLE TRGD55.PROJ
(PROJNO POSITION(1) CHAR(6),
PROJNAME POSITION(8) VARCHAR,
DEPTNO POSISION(33) CHAR(3))
Reorganizes tablespace to reclaim fragmented space
and imporve access performance
Alter the physical space parameters for the
tablespace
Unload data in a format acceptable by the LOAD
utility
Reorganize tablespace or a partition
REORG Utility
Input:
Name of tablespace or partition or index to be
reorganized
Output:
Reorganized tablespace and / or indexed
Table data in LOAD format
REORG Utility
Phase Flow:
UTILINIT
UNLOAD
RELOAD
SORT
BUILD
UTILTERM
RUNSTATS Utility
Gathers information about data in table spaces and
indexes and updates DB2 catalog.
Use RUNSTATS when
A table is loaded
A table is reorganized
An index is created
Extensive modifications done on table space
RUNSTATS Utility
Input
Tablespace for which stastics is to tbe
updated / reported
Output:
Report containing new statistics
Updated DB2 catalog tables
RUNSTATS Utility
Phase Flow:
UTILINIT
RUNSTATS
UTILTERM
COPY Utility
Creates backup copies of a
tablespace or s single
partition
Reset copy pending status
Two types: Full image copy,
Incremental image copy
COPY Utility
Input:
Name of tablespace or partition to be
copied
Output
Asequential dataset containing the
image copy
SYSIBM.SYSCOPY updated
Copy pending status reset
UNLOAD Program
Sample JCL
Sample Utilit JCL
eds.com
Contact information or Web site URL can be added here
Download the new PowerPoint presentation tutorial at:
http://infocentre.eds.com/workplace/how/present/present_main.html
DDL – CREATE Storage Group
Syntax:
CREATESTOGROUP Stogroup-name
VOLUMES (vol1, vol2,…)
VCAT catalog–name
(PASSWORD password)
DDL – ALTER Storage Group
Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES ( vol4, vol5, …)
REMOVE VOLUMES (vol1, vol2, . . . )
Syntax:
CREATE DATABASE database–name
(STOGROUP stogroup–name)
(BUFFERPOOL bufferpool–name)
* specified in KB
DDL – CREATE TABLESPACE Parameters
ERASE:
LOCKSIZE:
BUFFERPOOL:
CLOSE:
* Indicates whether data sets associated with tablespace;should be closed when there are no
current users of tablespace
* Default is YES
DDL – CREATE TABLESPACE Parameters
FREEPAGE:
PCTFREE:
CREATE TABLESPACE
IN DSN8DP2AP
USING STOGROUP DSNS6200
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BP0
DDL – ALTER TABLESPACE
Syntax : (Format 1)
Syntax : (Format 2)
COLUMN- definition:
PRIMARY KEY(colname1,colname2,…)
DDL- CREATE TABLE
foreign-key definition:
Other parameters:
Example
Syntax :
Syntax:
Syntax :
Example
DATA
MANIPULATION
LANGUAGE
DML Overview
DML verbs are:
ko m m
ko ko ko
m k
ko m
o
DML – SELECT Statement
Syntax:
Scalar Expressions
(LENGTH (SNAME) – 1 * 2
SALARY + COMMISSION + BONUS
Search Condition
(SUBSTR (SNAME,1,3) = ‘VIJ’
AND
CITY = ‘MADRAS’
DML- SELECT Statement
• SELECT S =
FROM SUPPLIERS
WHERE CITY = ‘MADRAS’
AND STATUS > 20;
DML – SELECT Statement
•Simple Subquery
•SELECT SNAME FROM SUPPLIER WHERE S# IN (SELECT S# FROM
SHIPMENT WHERE P# = ‘P2’)
DML – SELECT Statement
UNION
Union operation on union-compatible sets of rows
Labeled Duration:
•N units
Special Registers:
•CURRENT TIMEZONE
•CURRENT DATE
•CURRENT TIME
•CURRENT TIMESTAMP
DML – DATE / TIME Arithmetic
Examples:
• DATE(‘8/17/1996’) – DATE(’10/28/1996’)
• START_DATE + 1 YEAR + 6 MONTS
• CURRENT TIMESTAMP + 1 SECOND
• START_TIME – END_TIME < 080000
DML – INSERT Statement
Syntax:
INSERT
INTO table[ (column [, column] …)]
Values (literal [,literal]….)
Or
INSERT
INTO table [ (column[, column] …)]
subquery
DML – INSERT Statement
Examples
INSERT
INTO PARTS (P#, CITY, WEIGHT)
VALUES (‘P7’, ‘CALCUTTA’, 24)
INSERT
INTO PARTS
VALUES (‘P8’,‘SPROCKET’,‘PINK’,14,‘SHIMLA’)
DML – INSERT Statement
INSERT
INTO TEMP (P#, TOTQTY)
SELECT P#,SUM(QTY)
FROM SHIPMENT
GROUP BY P#
DML – INSERT Statement
Insert with Referential Integrity
INSERT
INTO SHIPMENTS.S#, P#, QTY)
VALUES (‘S20’,….)
Syntax:
UPDATE table
SET column = scalar-expression
[, column = scalar-expression]
[WHERE search-condition]
DML – UPDATE Statement
UPDATE PARTS
SET COLOR =‘YELLOW’
WEIGHT = WEIGHT + 5
CITY = NULL
WHERE P# = ‘P2’
UPDATE SUPPLIER
SET STATUS = 2 * STATUS
WHERE CITY = ‘MADRAS’
DML – UPDATE Statement
UPDATE SHIPMENT
SET QTY = 0
WHERE ‘LONDON =
(SELECT CITY FROM SUPPLIER
WHERE SUPPLIER.S # =
SHIPMENT.S#)
DML – UPDATE Statement
UPDATE SHIPMENTS
SET S# =‘S20’
WHERE …
SUPPLIERS.S# should have an entry S20
UPDATE SUPPLIERS
SET S# = ‘S20’
WHERE S# = ‘S1’
DML – DELETE Statement
Syntax: