db2 application modified
TRANSCRIPT
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 1/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 2/150
DB2 Objects
There are two types of elements or objects
Data Objects
Accessed under the user’s direction and
by which the user’s data is organized.
System Objects
Controlled and used by DB2
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 3/150
DB2 ObjectsDB2 Objects
Data Objects
Tables
Indexes
Views Tablespaces
Databases
Storage Groups
System Objects
DB2 Catalog
DB2 Directory
Active & Archive Logs Boot Strap Data Set
Buffer Pools
Locks
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 4/150
What is a Database ? ‘Is a repository for stored data’ - C.J.Date
What is Data ? ‘A representation of facts or instruction in a form
suitable for communication’ - IBM Dictionary
What is a database system ?An integrated and shared repository for stored data orcollection of stored operational data used byapplication systems of some particular enterprise.
Or
‘Nothing more than a computer-based record keepingsystem’ .
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 5/150
System Objects
DB2 Catalog
Consists of tables of data about every object defined in the DB2 system.
When an object is created, altered or dropped, a row is inserted, updated
deleted in the Catalog.
DB2 Directory
Contains information required to start DB2 & for its normal operation
Cannot be accessed using SQL
Directory objects are not described in DB2 catalog
Bootstrap Dataset
Contains inventory of all active and archive log datasets.
During installation of DB2, two BSDS datasets are created, kept in different volumes.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 6/150
Active & Archive Logs
DB2 records all data changes and significant events in active logs as t
occur. In case of failure, it uses this data to recover the lost information.
When the active log is full, DB2 copies the contents of the active log to a DA
or magnetic tape data set called archive logs.
Buffer Pools
Are areas of virtual storage which DB2 uses during execution of an applica
program or an interface SQL, to temporarily store pages of tablespace
There are four different bufferpools named BPO, BP1, BP2, and BP32.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 7/150
Locks
DB2 guarantees data integrity by using several locking mechanisms. These strategies pe
multiple users from multiple environments to access and modify data concurrently without lo
data integrity.
DB2 supports locking at three levels. Table Space Level, Table Level and Page Level.
DB2 uses locks to control concurrency & prevent inconsistent data.
Data Objects
Tables
All data is stored in tables.
A table is a collection of rows, all having same columns
Rows are records and Columns are fields.
Intersection of a column & row is a Value
SQL is used to access data in DB2 tables.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 8/150
Indexes
An ordered set of pointers to the data in DB2 table
Stored separately from the table
Each index occupies its own space
Used to Improve performance; Ensure Uniqueness
Multiple indexes can be defined on a table
A table having a primary key will necessarily have a primary unique index.
Views
Is a virtual table derived from one or more base tables
The view definition is stored in a catalog.
Alternate way of representing data that exists in one or more tables
Can include all or some of the columns from one or more base tables
Indexes on Base table can improve the performance operations on the views
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 9/150
TablespacesIs the physical space used to hold one or more tables
Consists of 1 to 64 VSAM LDS can contain upto 64 GB of data
Three types of tablespaces are
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 10/150
Database
A Set of DB2 objects (tables, indexes, tablespaces & views)
One database for one application recommendedDefault Database is DSNDB04
Storage Group (STOGROUP)
A set of Volumes on DASD. Volumes hold the data in which
tables and indexes are actually stored.Up to 133 DASD volumes can be assigned to a single
STOGROUP.
DB2 allocates storage for tablespaces and indexes. When a
tablespace is created, DB2 defines the necessary VSAMdatasets using IDCAMS.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 11/150
STOGROUP
It is a collection of direct access volumes , all of the same device
type.
The option is defined as a part of table space definition.
When a given space needs to be extended, storage is acquired from
the appropriate STOGROUP.
Max. 133 volumes in a single database.
Syntax:CREATE STOGROUP MAPSG
VOLUMES(SMS001)
VCAT DSNCAT;
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 12/150
DATABASEA collection of logically related objects like
Tablespaces - Indexspaces - Tables etc
Not a physical kind of object – may occupy more than one disk space
A STOGROUP & BUFFERPOOL ( is buffer area used to maintain recently accessed
table & index pages) must be defined for each database.
STOGROUP and user-defined VSAM are the two storage allocation for a DB2 database
definition.
In a given database, all the spaces need not have the Same STOGROUP.
More than one volume can be defined in a STOGROUP. DB2 keep track of which volume was defined first & uses that volume.
Syntax:
Create Database DBMAP STOGROUP MAPSG;
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 13/150
TABLESPACES
Logical address space on secondary storage to
hold one or more tables.A ‘SPACE‘ is basically an extendable collection of
pages with each page of size 4k or 32k bytes.
It is the storage unit for recovery & reorganizing
purpose.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 14/150
simple Tables paces
A simple tablespace can contain one or more tables.A single page of a simple tablespace can containrows from all the tables defined to thetablespace.
In general only one table should be defined persimple tablespace.One table space can be up 64 billion bytesPage size 4kb to 32 kbEach row contains 127 tuples rowsLock is at page levelHere data integrity will be there but data
concurrency will not be there
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 15/150
simple tablespace can contain more than one stored table,though one is usually the best option.
It normally consists of only one VSAM ESDS and maycontain one or more table.
Reading the data of one table requires a sequential read othe Tablespace(tablespace scan) thus increasing I/O anddegrading performance.
Concurrent access to tables in the same tablespace cancause lengthy response delays
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 16/150
LOCKSIZE - indicates the type of locking DB2 performs for the given
TS. (PAGE/TABLE/TABLESPACE)
USING - method of storage allocations –Stogroup or VCAT
PCTFREE - % of space available for future inserts.
FREEPAGE - no. of pages after which an empty page is available.
BUFFERPOOL – BP1,BP2, BP32K
CLOSE – YES/NO- whether the underlying VSAM datasets be closed
each time the table is used.
ERASE – YES/NO - whether physical DASD where the TS reside to bewritten with binary zeros when the TS is dropped.
NUMPARTS - For partitioned tables paces
SEGSIZE - For segmented tables paces
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 17/150
Create simple tablespace
SYNTAXCREATE TABLESPACE SSSVIJTS IN SSSVIJDB USINSTOGROUP
ST0R1PRIQTY 30720SECQTY 10240LOCKSIZE TABLEBUFFERPOOL BP0
CLOSE NO;character: A Cobol word must be formed from followingcharacter
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 18/150
Simple table space
Page1
Table Row 1
Table 1 Row 2
Table 2 Row 1
Page 2
Table 1 Row 3
Table 3 Row 1
Table 2 Row 2
Page 3
Table 1 Row 4
Table 2 Row 3
Table 2 Row 4
Page 4
Table 3 Row 2
Table 3 Row 3
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 19/150
Segmented Tablespaces
The pages within a tablespace are organized into segments and each segment holds
from only one table.
Can hold more than one table. A segmented tablespace is the most efficient type of tablespace for most of the
development efforts.
The space is divided in to equal-sized groups of pages calledsegments, and each segment can contain rows from only one table
Each segment is a group of 4 to 64 pages.Provides improved performance, concurrency and space managem
for multiple tables in a single table space. Related tables can be efficiently placed together in one Table
space.
S t t bl
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 20/150
Segment table space
Segmented table space
Segment 1 Segment 2
Page 1 Page 2 Page 3 Page 4
Table 1 Row 1
Table 1 Row 2
Table 1 Row 3
Table 1 Row 4
Table 1 Row 5
Table 1 Row 6
Table 2 Row 1
Table 2 Row 2
Table 2 Row 3
Table 2 Row 4
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 21/150
Create segment
SYNTAX
CREATE TABLESPACE KSATSIN SSSVJDB USING STOR1
PRIQTY 52
SECQTY 20
ERASE NOSEGSIZE 32
LOCKSIZE PAGE
BUFFERPOOL BP1
close YES;
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 22/150
Partitioned Tablespaces
The tablespace is divided into partitions, and each
partition is stored in one VSAM data set.A partitioned tablespace is divided into componentscalled partitions.
Each partition resides in a separate physical
dataset. DB2 permits 1 to 64 partitions pertablespace.
Only one table can be defined in a partitionedtablespace
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 23/150
Partitioned Tablespaces
SYNTAX
CREATE TABLESPACE SALESHX IN SSSVJDBUSING STOR1
PRIQTY 4000
SECQTY 130
ERASE NONUMPARTS 82
LOCKSIZE PAGE
BUFFERPOOL BP1
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 24/150
Partitioned table space
Partition 1 Partition 2
Page 1 Page 2 Page 3 Page 4
Table 1 Row 1
Table 1 Row 2
Table 1 Row 3
Table 1 Row 4
Table 1 Row 5
Table 1 Row 6
Table 1 Row 7
Table 1 Row 8
Table 1 Row 9
Table 1 Row 10
Table 1 Row 11
DB2 Threads
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 25/150
DB2 Threads
Controls Structures used by DB2 to communicate with an applicatio
program. Used to send requests to DB2, to send data from DB2 to the program, and
communicate the result of each SQL statement after it is executed.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 26/150
DB2 Operating Environment
All DB2 application types can execute concurrently by sharing the same Ddatabases.
A DB2 application executing under CICS is an on-line application and us
CICS facilitates to communicate messages.
A CICS/DB2 application can access DB2 data, IMS data, and VSAM data.
The combination of DB2 with CICS performs as a full functions DB/D
system & CICS serves as the transaction manager.
Structured Query Language (SQL)
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 27/150
Structured Query Language (SQL)
SQL is a high level language that provides a greater degree of abstraction than
procedural languages.
It is fashioned so that the programmer can specify what data is needed but n
not specify how to retrieve it.
Used to access data in DB2 tables.
Ways of executing SQL's
Foreground
Using SQL Processor Using File Input (SPUFI)
Using Query Management Facility (QMF)
Background
By embedding them in application programs written in C, Cobol, Fortran,
Assembler, PL/1, etc.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 28/150
Data Definition Language (DDL)
DDL - Data Definition Language statements to define or create the objects ofdatabase.
CREATE, ALTER, DROP
Data Manipulation Language (DML)
DML - Data Manipulation Language statements to manipulate data in tables.
SELECT, INSERT, DELETE, UPDATE
Data Control Language (DCL)
DCL - Data Control Language statements to GRANT and REVOK
authorization to user resources.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 29/150
Relational concepts
Relation : A table or FileTuple : Row contains an entry for each attribute
Attributes : Columns or the characteristics thatdefine the entity
Domain:. A range of values (or Pool)
Entity : Some object about which we wish tostore information
Null : Represents an unknown/empty value Atomic Value: Smallest unit of data; theindividual data value
DB2 Database Design
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 30/150
DB2 Database Design
DB2 Datatypes
Null:
All datatypes include the null value. The null value is a special value that
distinct from all other values and thereby denotes the absence of a value. It
NOT the same as 0 or blanks.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 31/150
Date format
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 32/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 33/150
Time format
DB2 Datatypes & Lengths
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 34/150
NOT NULL: Value must be given
NULL: If Value not given it is marked unknown
NOT NULL: If value not given DB2 fill default value
WITH DEFAULT: Numeric Becomes Zero, Character Becomes Blank, Date becomes Curr
Date, Time becomes Current Time, Timestamp becomes Current Timestamp.
If Nulls are allowed, internal storage length is increased by 1 byte
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 35/150
Primary & Foreign Key Concepts
Key identifies a row of data
Keys can be composed of more than one column (composite keys)
Two Types of keys
Primary Key Identifies its own row
Must be unique
Foreign Key Identifies a row of related data
Need not be unique
Tables are related only by primary & foreign keys
Table with the primary key is called parent table Table with the foreign key is called a child table or a dependent table.
Referential Integrity Rules
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 36/150
Referential Integrity or Relation Integrity is another elementary data integrity ru
of the relational model.
Referential Integrity defines the relationships among different columns an
tables in a relational database.
It is called referential integrity because the values in one column or set
columns refer to or must match the values in a related column or set of column
A mechanism that ensures data integrity between tables related by Primary
Foreign Keys
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 37/150
Insert Rules
When inserting a row with the foreign key, DB2 checks the values of the foreig
key columns against the value of the primary key columns in the parent table.
new Primary Key can be inserted as long as it is unique.
Update Rules
When updating foreign key values DB2 performs same checks as when it is inserting a row with
foreign key.
Delete RulesCascade: When a row of the parent table is deleted, any related rows in th
dependent table are also deleted.
Restrict : Rows of parent table that have dependent rows cannot be deleted
Set Null: When a row of a parent is deleted, the corresponding values of thforeign key in any dependent rows are set to null.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 38/150
DDL, DML, DCL Commands
DDL Statements
Creating DB2 Objects
CREATE Statement is used to create all DB2 data objects.
• General format
CREATE Object, Object Name Option - List
Object STOGROUP | DATABASE | TABLESPACE | TABLE | VIEW | INDEX
Object Name: name of the DB2 object
Option - list: Options for the object to be defined
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 39/150
CREATE TABLE
This statement is used to create objects
SYNTAX : For Creating a Table
CREATE TABLE <tabname> (ColDefinitions)
PRIMARY KEY(Columns) / FOREIGN KEY
UNIQUE (Colname) (referential constraint)
CHECK (colname relational operator value)(check constraint)
[IN Database.Tablespace Name ]
CREATE TABLE
This statement is used to create objects
SYNTAX : For Creating a Table
CREATE TABLE <tabname> (ColDefinitions)
PRIMARY KEY(Columns) / FOREIGN KEY
UNIQUE (Colname) (referential constraint)
CHECK (colname relational operator value)(check constraint)
[IN Database.Tablespace Name ]
Create Tables
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 40/150
CREATE TABLE EMPTAB (EMPNO INTEGER(5) NOT NULL
EMPNAME CHAR(25) NOT NULL
DESIG CHAR(25) NOT NULL
SALARY DECIMAL(7,2)
DOB DATE NOT NULL
IN GSLDB.GSLTS
Create Index
CREATE UNIQUE INDEX index name ON table name (FLD 1 ASC/DESC, FLD 2ASC/DESC)
Example: CREATE UNIQUE INDEX EMPIDX ON EMPTAB (EMPNO ASC);
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 41/150
Create View
CREATE VIEW view name AS
SELECT FLD 1, FLD 2 ….. From table-name
WHERE condition (WITH CHECK OPTION)
Example: CREATE VIEW EMPV AS SELECT EMPNO, EMPNAME FROM EMPTAB
WHERE dept name = ‘TRG’
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 42/150
to Add new column
to Add Primary Key
to DROP Primary Key & Foreign Key
to Add Referential Constraints
Example:
ALTER TABLE EMPTAB ADD ADDRESS CHAR(30);
Alter Table
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 43/150
Notes:
Adding a primary key in a table puts the table in a
incomplete state until a unique index is created on tha
particular column. Dropping a primary key on a parent tabl
drops all references to dependent tables.
DB2 does not allow deletion of a column from a table. DB
does not allow the characteristics of the column to b
changed.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 44/150
Provides effective control over the resources at require
levels, either at the row level or at the column level.
• Allows centralization / decentralization of control at require
levels.
• DB2 users may be allowed to control the use of resources
without permission/assistance of Database Administrators.
• Control over DB2 objects and data is achieved throug
GRANT and REVOKE statements.
DCL Statements
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 45/150
Revokes privileges from authids
General format
REVOKE authorization ON object object name FROM
authid / PUBLIC
Example:REVOKE SELECT ON TABLE EMPTAB FROM TRGE010;
Revoke
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 46/150
Grants privileges to Authorization Ids.
General format
GRANT authorization ON object object name to authid / PUBLIC [WITH GRANT OPTION ]
Can be executed from an application program or can be executed interactively using SPUFI
QMF
Authorization for table can be SELECT, INSERT, UPDATE, DELETE, ALTER, INDEX or ALL
For update, authorization can be given on specific columns also.
WITH GRANT OPTION allows the grantee to grant privileges to others.
Example: GRANT SELECT ON TABLE EMPTAB TO TRG010;
Grant
DML Statements
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 47/150
DML Statements
Insert
To insert values into the fields of a table
There are 2 types of INSERT statements.
INSERT statement with VALUES clause is used to insert a single row.
INSERT with SELECT statement is used to insert one or more rows.
General Format:
INSERT INTO tablename (col1…) VALUES (val1…);
INSERT INTO tablename (col1…) sub-select;
Example: INSERT INTO TABLE1 VALUES (005, ‘RAM’, ‘MKR’, ‘SALES’);
EMPNO Name GRPID DESIG
005 RAM MKR SALES
Example: INSERT INTO TABLE1 SELECT* FROM TABLE2;
Update
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 48/150
Used to change any value in a table
Changed from MKR to FIN
If WHERE clause is not used, all records are changed to ‘FIN’ GRPID
So the record changes to:
Example: UPDATE TABLE1 SET GRPID=‘MKR’ WHERE EMPNO=005;
EMPNO NAME GRPID DESIG005 RAM FIN PRG
Select
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 49/150
• ‘SELECT‘ statement is used to retrieve all or part of the records in a table.
‘WHERE‘ clause is used to specify the search criteria. If no criteria is specified, all the recor
are retrieved. Example: Table1
EMPNO NAME GRPID DESIG
001 JOSEPH MKR SMG
002 SAM FIN GM
003 RAJA SALES MGR
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 50/150
Selecting all Columns
The same answer is got even if we give SELECT EMPNO, NAME, GRPID, DESIG from TABLE
SELECT* FROM Table1 ‘*’ – to specify all columns
EMPNO NAME GRPID DESIG
001 JOSEPH MKR SMG
002 SAM FIN GM
003 RAJA SALES MGR
Selecting few Columns only
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 51/150
Conditional Select
WHERE clause is used to select data from only the rows that meet certain conditions. A WHERE
clause specifies a search condition that, when evaluated against a row, yields TRUE or FALSE o
UNKNOWN.
Selecting unique rows
In: To select from a list of values
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 52/150
Between: To select a range of values
Like: To select based on a subset of characters
Not: Negate a condition
Any
Is same as IN when given as =ANY
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 53/150
Is same as IN when given as =ANY
Joins
Joins are used to select data from multiple tables
Example: Table2
We are joining table 1 and table 2 to get the information of manager(s) only.
Cartesian Product
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 54/150
‘Cartesian product ‘ is the result of a join that does not specify matching columns.
Subquery
Used to nest SELECT statements
When one or more select statements are nested, it is referred to as sub query
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 55/150
To get the information for all the managers
To get the information about the 'FIN' group's manager
Union
UNION bi f i i l d f ll h i i h b h
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 56/150
UNION combines two sets of rows into a single set composed of all the rows in either or both o
the two original sets. The two original sets must be ‘union-compatible‘ (i.e.)
The two sets must contain the same number of columns.
Each column of the first set must be either the same data type as the corresponding column
the second set or convertible to the data type of the corresponding column of the second set.
Outer Join
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 57/150
When we want both matching & non - matching rows returned for one or more of the tables be
joined, we use Outer Join.
Sorting & Grouping
The ‘ORDER BY‘ clause sorts result of a query in the specified order (ascending or
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 58/150
The ORDER BY clause sorts result of a query in the specified order (ascending or
descending) for each column.
The ‘GROUP BY ‘ clause sorts the resultant rows to apply functions that consolidate the data
By grouping data, users can use statistical functions on a column [Example: AVG, SUM, MIN
MAX]
It does not do any sorting. For sorting, ORDER BY clause should be used.
After having grouped using the ‘GROUP BY ‘ clause to eliminate non - pertinent data we use
Having ‘ clause. The HAVING clause is to specify conditions for the GROUP BY clause.
Note: Default Order is Ascending.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 59/150
Note: If there are 50 ‘MKR’, 50 ‘FIN’ & 50 ‘SALES’ records, they will be grouped together a
displayed.
Table 3:
Aggregation& Column Functions
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 60/150
Column functions compute from a group of rows and return a single value for a designat
column or expression.
Example: AVG, COUNT, MAX, MIN, SUM
AVG
To find the Average of a column specified or expression given as the argument
Count
To count the number of rows, use distinct keyword to count only the number of distinct values
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 61/150
a given column.
Max
Max function returns the largest value in the specified column or expression.
Min
Min function returns the smallest value in the specified column or expression.
Sum
This returns the accumulated total of the specified column or expression.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 62/150
Delete
To delete a record or set of records or all records
General Format:
DELETE FROM table name WHERE search-condition;
If WHERE clause is not used, all records are deleted.
If WHERE clause is not used, all records are deleted.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 63/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 64/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 65/150
DB2 & TSO
TSO or Timesharing Option, is one of the environments from which DB2 da
can be accessed.
TSO enables the users to interact with MVS using an on-line interface that either screen or panel driven.
The Interactive System Productivity Facility (ISPF) provides the mechanism f
communicating by panels, which is the common method for interaction betwee
TSO and application users.
Jcl to submit embedded sql000100 //MA24A JOB ,,NOTIFY=MAPLE24,MSGLEVEL=(1,1)000200 // JCLLIB ORDER=MAPLE24.DB2.PDS000300 //STEP01 EXEC PROC=DSNHCOB WSPC=500 MEM=SIMPLE user=userid To identify the library
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 66/150
000300 //STEP01 EXEC PROC=DSNHCOB,WSPC=500,MEM=SIMPLE user=userid To identify the library000400 //PC.SYSIN DD DISP=SHR,DSN=MAE24.DB2.PDS(&MEM) path for the source code location000410 //PC.SYSLIB DD DISP=SHR,DSN=MAE24.DB2.PDS path for the DCLGEN000420 //PC.DBRMLIB DD DISP=SHR,DSN=MAPLE24.DBRM.PDS(&MEM) path for the DBRMLIB000500 //LKED.SYSLMOD DD DISP=SHR,DSN=MAPLE24.RUNLIB.LOAD(&MEM) Path for the load module(generation)
000600 /*000700 //BIND EXEC PGM=IKJEFT01,DYNAMNBR=20,COND=(4,LT) DB2 utility000710 //STEPLIB DD DISP=SHR,DSN=DSN710.SDSNLOAD000900 //SYSTSPRT DD SYSOUT=(*)001000 //SYSTSIN DD *001100 DSN SYSTEM(DSN2) To connect to TSO001200 BIND PLAN(MAPLE24P)- plan to be created with in userid001300 MEMBER(SIMPLE)- Application member name001400 ISOLATION(CS) - cursor stability locks amount of page where Db2 resides
001500 RELEASE(C) - Close the cursor
001600 EXPLAIN(NO)- Find the optimum path001700 OWNER(MAPLE24)- userid001800 LIB('MAPLE24.DBRM.PDS')001900 RUN PROGRAM(SIMPLE) PLAN(MAPLE24P)-002000 LIB('MAPLE24.RUNLIB.LOAD')002100 /*002110 //002200 //SYSIN DD *002301 /*002310 //
002340 //
SPUFI
SPUFI (SQL Processor Using File Input) reads the SQL statements contained as a text in
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 67/150
sequential file, processes those statements and places the output in the output dataset specif
in the browse mode. The screen is self explanatory and the only inputs the user has to give
the input file name where the SQL statements are placed and the output file name where t
results have to be placed. SPUFI supports the online execution of SQL statements from a T
terminal.
DCLGEN CommandThe DCLGEN or Declaration Generator Command is used to produce a COBOL copybo
which contains a SQL DECLARE TABLE statement along with the WORKING-STORAGE ho
variable definitions for each column of the table. When the DCLGEN command is issued D
reads catalog to determine the structure of the table and builds the COBOL copybook.
Preparation Steps
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 68/150
SOURCE
DB2
PRECOMPILESQLNON
SQL
COMPILE
&
LNKEDIT
DB2
BIND
LOAD
MODPLAN
CATALOG
* *
* *
* =TIMESTAMP
Program Execution
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 69/150
LOADMOD
PLAN
DB2DL/I
or
VSAM
DB2
TABLESOTHER
DATA
CALLEXEC
DB2
TABLES
DB2L/I
or
VSAM
OTHER
DATA
DB2 Precompile Comments
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 70/150
Separates SQL from Non-SQL (Database Request Module)
Checks for errors
Does not access DB2 catalog
Can add code from Libraries
Timestamps both outputs
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 71/150
BIND Comments
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 72/150
Checks for errors, using DB2 catalog
Checks authorisation
Develops Access strategy for each statement
Stores strategies as plan (reusable without repeating bind
Pre-compilationPre-compiler Functions:
Program used: DSNHPC
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 73/150
Program used: DSNHPC
INPUT EMBEDDED SQL PROGRAM
OUTPUT
Modified source
DBRMLIB – Database Request Module
Other Sources needed:
DCLGEN: This produces modules that can be included in a program. It builds a COBOL copybook.
Expands the DB2 related INCLUDE statements.
Checks the SQL syntax.
Separates SQL from NON-SQL statements and places SQL statements in Database Request Mod
(DBRM)
Places TIMESTAMP in the Modified source in the DBRM member and load module.00
Compile
Program Used: IGYCRCTL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 74/150
INPUT Modified Source Program; OUTPUT OBJ Module
Other Sources needed: COPYLIBS
Process:
The COPYLIB members will be expanded.
The COBOL syntax will be checked.
Places time stamp written in precompiler step in OBJ module.
Link EditProgram Used: IEWL
INPUT OBJ Module; OUTPUT Load Module
Process:
The executable load module is produced
Subprogram exists will be merged along with system libraries
Places the timestamp written from the precompiler step in the load module.
BindProgram Used: IKJEFT01
INPUT DBRM LIB produced in precompiler step
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 75/150
INPUT DBRM LIB produced in precompiler step
OUTPUT PLAN
Function: Reads the SQL statements from DBRMs and produces a mechanism to access da
from tables.
Parameters given while binding:
1. Owner, Qualifier
2. Action (REPLACE/ADD)
3. Isolation (CS/RR)
4. Acquire (USE/DEALLOCATE)
5. Release (COMMIT/DEALLOCATE)
6. Validate (BIND/RN)
7. Explain
8. Flag.
Owner: Name of the owner who created the PLAN
Qualifier: Name where the table reside
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 76/150
Action: Add or Replace the existing plan (BINDADD & BINDREPLACE)
Isolation: This determines the mode of page locking implemented by the programs as it runs.
CS – Cursor Stability:
Releases the page locks as soon as another page is accessed or an COMMIT is issue
Improves concurrency.
RR – Repeatable Read (DEFAULT):
Does not releases the page locks until a COMMIT is issued.
Acquire: This determines the mode of table space locking implemented by the program as
runs.
Use: Table space locks are acquired when the table space is accessed.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 77/150
Allocate: Table space locks are acquired when the plan is allocated.
Release:
Commit : Table space locks are released at COMMIT or ROLLBACK time.
Deallocate: Table space locks are released only when the plan finishes and is deallocated.
Validate: Method of checking for the existence and validity for DB2 access tables a
authorization
Bind – Validates at Bind time; Run – Validates at run time.
Flag: Returns informational, warning, error and completion messages.
DB2 Application Programming Concepts
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 78/150
pp g g p
Data Base Request Module (DBRM)
DBRM is a module containing SQL statements from the source program, whi
have been extracted by the DB2 Pre-compiler.
The module is stored as a member of a partitioned data set.
The DBRM is used as input to the BIND process
Bind
Bind reads SQL statements from DBRM s and produces a method to access data as directed b
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 79/150
the SQL statements being bound.
It stores this access method as Plan
Two types of Binds - BIND PLAN, BIND PACKAGE
BIND PACKAGE accepts a DBRM as input and produces a SINGLE package.
A package is not executable. Packages should be bound into a plan before executing.
Output of BIND PLAN is the application plan containing the executable logic giving the access
path to DB2 data.
BIND also performs Syntax checking of SQL statements, Checking of the DB2 table and colum
catalog Information, Authorization Validation.
Compile & Link Edit• Modified source program produced by the DB2 pre-compiler is the input for COBOL compiler.
Compiled source code is given as input to Linkage editor.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 80/150
Linkage editor produces the executable load module.
Appropriate DB2 host language interface module must be included in the link-edit step.
Running a DB2 Program
Program preparation steps will produce two separate physical components- DB2 Plan, Link-Edited Lo
Module.
To run an Application program containing SQL statements, the name of the Plan should be specified.
At execution time, DB2 checks for the compatibility of the Plan and the load module by comparing
TIMESTAMP.
DB2 programs can be executed in
Batch / TSO, Using Call Attach Facility, CICS
Embedded SQL
SQL statement are embedded anywhere in the application program. These are analyzed by DB2 p
compiler & replaced by equivalent statements in host language
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 81/150
p p y q g g
In addition to data definition/manipulation statements, SQL statements unique to application progr
coding are provided. These include support for Declaration tables, Include statements, S
Communications Area, usage of Host Variables within SQL statements & Cursor tables. DB2 application programs may be coded in COBOL, FORTRAN, PL/I and ASSEMBLY language.
Each statement is delimited i.e. each SQL is enclosed in an EXEC SQL, END-EXEC block
Data Values can be gathered from host program variables
Multiple rows of table can be accessed through a CURSOR
DB2 describes results of execution in SQLCA
End Delimiter varies by Host Language. For COBOL, it is END-EXEC.
SQL/COBOL Program Components
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 82/150
Working Storage:
Host program variables are defined here to hold data. These variables areferred in the SQL statements in the Procedure Division.
Procedure Division:
• SQL statements to access and manipulate data are coded here. The
statements reference DB2 tables and host program variables.
• SQL statements begin with EXEC SQL and end with END-EXEC.
SQL Communication Area:SQLCODE Field tells result of last executed SQL request
Examples: 000 Successful
+100 No more rows found
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 83/150
+100 No more rows found
- 530 New Foreign key value is invalid
SQLCODE field should checked after each SQL statement If SQLCODE is less than 0, an SQL error was encountered.
Including TABLE DECLARATION
• SQL provides a facility to copy source code from a library into application program, by coding INCLU
statement.
• The INCLUDE statement directs DB2 pre compiler to copy source code into the program. This functionvery similar to COPY statement in COBOL.
• INCLUDE statement is normally coded to copy DCLGEN outputs into the program’s working-stora
section. It can also be used to copy SQL or COBOL statements in the Procedure Division. However,
include code must not contain Include statements within it. I.e. nested INCLUDE.
• The general statement format is
• EXEC SQL INCLUDE source code name• END-EXEC
Host Variables, Null Indicator Variable
Host variable is an area of storage allocated by the host language and referenced in an SQ
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 84/150
Host variable is an area of storage allocated by the host language and referenced in an SQ
statement.
Host variables are defined and named using Host Language Syntax
For COBOL, host variables are defined in Data Division or Linkage Section
A ‘ : ‘ should precede the host variables used in embedded SQL statements
Host variables can be used as:
A host variable cannot be used for table names, column names, SQL verbs etc.
A host structure is a COBOL Group level data area consisting host variables for all colum
returned by SELECT statement. OCCURS clause cannot be used while declaring su
structures.
Notes:• For host variables not within a host structure, use COBOL level numbers 01 or 77.
• Variable character fields are defined as a 02 group level specifier, and two 49 lev
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 85/150
specifiers. One is the length specifier, and other is the actual data field.
• While inserting data into a variable character field, the actual number of characters instead
indicated by the length specifier.
• While retrieving data from a variable character field, the actual number of characte
returned in the data field is indicated by the length specifier.
In the above example DCLDEPT is a Host Structure containing corresponding Host variables
DEPTNO, DEPTNAME & LOCATION
Host Structure
A series of variables referenced as a unit is called a structure.
• In a COBOL 01 (group) level data structure, representing all column selected in SQL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 86/150
statement. The 01 (group) level data name is prefixed by a colon
• Is coded in a SQL statement in place of elementary level fields.• Can have a maximum of two levels.
• When elementary fields have duplicate data names, they must be qualified with the relevan
structure name.
• The general coding format is: Structure Name.Field Name
Note:
• For data variable within a host structure use COBOL level numbers 02 through 48.
•Coding FILLER within a host structure makes the structure invalid.
Null Indicator VariablesIndicator variable is a 2 Byte integer S9 (4) Comp.
• Declared similar to Host variables.
• Negative value for Indicator variable means the associated column value has a NULL value.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 87/150
• If a column is truncated, length of the field is returned in the Indicator variable.
• Can be declared as an array of Indicator variables. OCCURS clause can be used.
• To associate Null Indicator variable with a particular host variable for a column, code the indicator variab
immediately after the Host variable, preceded by a colon.
• Can be used along with Host variables in
• Set Clause of UPDATE Statement
• VALUES Clause of INSERT Statement
• INTO Clause of SELECT or FETCH Statement
SQLCODERegardless of whether the application program provides an SQLCA or a stand-alone variab
SQLCODE is set by DB2 after each SQL statement is executed. DB2 conforms to the ISO/AN
SQL standard as follows:
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 88/150
SQL standard as follows:
• If SQLCODE = 0, execution was successful.• If SQLCODE > 0, execution was successful with a warning.
• If SQLCODE < 0, execution was not successful.
• SQLCODE = 100, "no data" was found. For example, a FETCH statement returned no d
because the cursor was positioned after the last row of the result table.
Using Select - Into Clause• Only one row from the table is returned
• Example:
MODIFIED
SOURCE
MODULEb
DBRM
SOURCE
MODULE
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 89/150
COMPILER
COMPILER
OBJECT
MODULE
EDITOREDITOR
LOAD
MODULE
OTHER
OBJECT
OTHER
OBJECT
DB
APPLICATION
PLAN
BIND BIND
PACKAGE
BIND BIND
PRECOMPILER
PRECOMPILER
LIST OF
PACKAGE
LIST OF
PACKAGE
Cursor Processing
In the Embedded SQL application program development, if select returns mo
than one row of information then we have to use cursor’s since the progra
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 90/150
than one row of information then we have to use cursor’s, since the progra
cannot process all the rows at once. It can process only one row at a time.Following operations can be performed on a CURSOR
DECLARE
OPEN
FETCH
CLOSE
Cursor can return zero, one or many rows depending on the Fetch condition.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 91/150
Static Embedded SQL
used when you know all the possible SQL statements that
might be written
Dynamic Embedded SQL
used when the SQL statements will be defined at
run-time (ie. they are not known in advance)
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 92/150
select name, ?, ?
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 93/150
from ?
where name = ‘jones’
select name, agefrom employee
where name = ?
Requires dynamic SQL
Can use static SQL
The syntax of the Declare cursor statement
Exec Sql
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 94/150
Declare cursor-name Cursor [with hold] for
Select [Distinct] col-spe[As result-col],[col-spe[As res-col]from table-name [ Where selection-cond] {[for update ofupdate-col[,update-col]..] [Order by sort-col [Asc/Des]]..}
End-Exec.
__________________________________________ _ With hold Prevents the cursor from being closed as a
result of a commit operation
Update-col
The name of the column for which you wantto enable updates
DECLARE Cursor syntax:
EXEC SQL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 95/150
EXEC SQL
DECLARE cursor FOR union-expression[ ORDER BY columns) ]
FOR [ FETCH ONLY | UPDATE OF
columns) ] ]END-EXEC.
Declare Cursor
To define and identify a set of rows to be accessed.
For updating / deleting a row FOR UPDATE OF option sho
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 96/150
For updating / deleting a row, FOR UPDATE OF option sho
be specified.
Cursor name cannot be a Hyphenated word
Example of Cursor Declaration
WITH HOLD clause can be used with DECLARE, to retain the cursor position beyond tcommit point.
Sql Fetch statement
Exec Sql{ |
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 97/150
Fetch cursor-name INTO {:host-var [, :host-var]…|:host-structure }
End-Exec.
________________________________________________________________
For eg:Exec SqlFetch custcur INTO :fname, :lname
End-Exec.
Open Cursor • Activates the cursor
• Rows are retrieved and stored in the result table
f f
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 98/150
• Pointer is positioned before the first record
• Example
Fetch Cursor
• Moves the contents of the selected row into Program Host Variables
• Points to the next row
• Cursor must be opened explicitly before it can be fetched.
• Example
Rows are sorted by invoice in descending sequence
Declare Invcur cursor for select invcust, invno ,invtotalform invtable where invcust = :custno order by invtotald
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 99/150
des
__________________________________________ __ Declare custcur cursor for select fname, lname from
custtablewhere state = ‘ca’ order by 2
__________________________________________ __
Declare invcur cursor for select invno, invdate,invtot+invtax As
Total from invtable order by total
SYNTAX FOR UPDATE statement
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 100/150
_________________________________
Exec Sql Update {table-name | view-name}
Set col-name = {:host-var| literal|expression|null}
[,col-name = {:host-var| literal|expression|null}]…[where {search-cond [with isolation-level]|
current of cursor-name}]
End-Exec.
EXAMPLE
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 101/150
EXEC SQL
UPDATE tableSET column = scalar-expression[, column = scalar-expression ] …..
WHERE CURRENT OF cursorEND-EXEC.
The keyword NULL puts a null value in a column, butthis can’t be used for a column that’s defined asNOT
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 102/150
NOT
NULL.If a Check Constraint has been defined for a column,the value that the column is set to must satisfy theconstraint.
If the value in the sqlcode field isn’t zero it means thatthe update failed so on changes were made to thetable. Sqlerrd(3).
The CURRENT OF phrase is used to update the4current row in a cursor controlled table.
Syntax for DELETE Statement
Exec Sql
Delete from {Table-name | view-name}
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 103/150
Delete from {Table name | view name}
[ Where {search-con [with isolation-level ] |Current of cursor-name}]
End-Exec.
_____________________________________________
For eg:
Exec Sql
Delete from invtable where custno = ‘30000’
End-Exec.
Exec Sql
Declare custcur cursor with hold for select custno,
addr city state from invtable where invcust < ‘3330’ for
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 104/150
addr, city, state from invtable where invcust < 3330 for
update of custno, addr, city, stateEnd-Exec.
__________________________________________________
Changes the row at the current cursor position.
Exec Sql
update invtable set custno = :custno, addr = :addr,
city = :city, state = :state Where
current of custcur
End-Exec.
syntax for Insert with ValuesExec sql Insert into (table-name | view-name)
[ col-name [, col-name]……)]
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 105/150
values({ :host-var | literal | null}……..)
End-Exec. ______________________________________________
Insert into customer values( :cust-no, :custname)
If a check constraint has been defined a column the
value that’s supplied for the column must satisfy theconstraint.
Sqlcode value of -803 means that the statement failed therow to be inserted contained a duplicate value in a
column that is defined unique
Insert with a sub query
Exec sqlInsert into (table-name | view-name)
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 106/150
Insert into (table name | view name)
[ col-name [, col-name]……)]select-statement [with isolation-level]
End-Exec. _________________________________________
Exec sqlInsert into oldcust-table select * from
customerwhere custno < ‘30000’
End-Exec.
Updating/Deleting of Row Fetched All columns to be updated should be included in the FOR UPDATE OF Clause in DECLAR
CURSOR Statement.
WHERE CURRENT OF Clause is used in UPDATE and DELETE statements to modify t
current row
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 107/150
current row.
UPDATE and DELETE statement must be preceded by a FETCH statement. Examples:
Close Cursor
CLOSES the Cursor
Releases the locks held by the cursor
DB2 automatically closes cursor when program terminates
COMMIT statement also closes all the cursors
-117 The number of insert values is not the same asthe number of object columns
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 108/150
-304 The value inserted is out of range-305 The null value cannot be assigned to output hosvariable number because no indicator variable isspecified
-805 Program not found in the PLAN-503 A column cannot be updated because it is notidentified in the update clause of the selectstatement of the cursor
Inserted or updated value invalid because index index-name
constrains columns of table such that no 2 rows can contain
-803
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 109/150
The precompiler-generated timestamp x in the load module is
different from the bind timestamp y built from the DBRM
-818
The Insert, Update, Delete, DDL or Authorization StatementCannot Be Executed Because the IMS/VS Transaction Is
Inquiry Only
-817
Result of an Embedded Select Statement Is a Table of More
Than One Row, or the Result of the Sub query of a Basic
Predicate Is More Than One Value
-811
duplicate values in those columns. Rid of existing row is X’rid’
Error Handling
WHENEVER statement used to enable automatic testing of return codes for subsequent SQL
statements
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 110/150
Affects all subsequent SQL statements until the next WHENEVER statement
General Format
Advanced SQL Topics
Dynamic SQL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 111/150
DB2 supports two types of SQL statements in an application program
- Static SQL
- Dynamic SQL
Static SQL are SQL statements embedded in a host language and bound before the progra
runs.
Dynamic SQL are SQL statements that are prepared and executed, while the programrunning.
Statements that are allowed as dynamic sql statement_____________________________________________
Statements u may be likely to use
DELETE INSERT SELECT UPDATE
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 112/150
DELETE,INSERT,SELECT,UPDATE.
Statements are not likely to use
ALTER,COMMERNT, COMMIT, CREATE, DROP,
EXPLAIN, GRANT, LABEL, LOCK TABLE, REVOKE,
ROLLBACK.
Cursor Processing Open, fetch, close.
Precompiler directives Declare Include Whenever.
Dynamic sql Execute Immediate Prepare .Execute Declare.
Static Vs Dynamic
For static SQL, the structure of the statement should be known beforehand, while dynamic SQ
allows complete flexibility in the structure of the statement.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 113/150
Static SQL can contain host variables; Dynamic SQL cannot host variables.
Static SQL are bound beforehand, while dynamic SQL are bound at runtime and hence ru
time overhead is greater.
Static SQL select statements can have ‘INTO’ clause whereas dynamic SQL sele
statements cannot have ‘INTO’ clause.
Examples of dynamic SQL:
SPUFI, QMF
These two accept almost any SQL statement, and process and execute the SQL statemen
dynamically.
Syntax for Sql EXECUTE IMMEDIATE
_____________________________________________
Exec Sql
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 114/150
Exec Sql
Execute Immediate :Host-varEnd-Exec.
Host-var Cobol host variables that contains the
statement string to be translated, bound and executed.
Must contain data compatible with the DB2 varchar
data type.
Sql prepare statement
Exec Sql
P d
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 115/150
Prepare parpared-statement-name
[Into Sqlda-name]
From :host-var
End-Exec.
Prepared statement Symbolic name 18 characters lon
u create to identify the prepared statement .Sqlda-name The name of an sqlda where informationabout the prepared statement will be stored
Host-var Cobol host variables that contains thestatement string to be translated, bound and associat
with prepared statement.
Where a host var would not used to allowed in a static
statement. [as in from ?]
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 116/150
As column specifications [ as in select ?,?,?]
As both elements in a comparison [as in where ? = ?]
As both elements of an arithmetic operation
[as in where invtotal =?+?]
Categories of Dynamic SQL
Non - Select SQL Statements
Fixed - List Select Statement
Varying List Select Statement
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 117/150
Varying -List Select Statement
Non-Select SQL Statements
The SQL statement is stored as a string.
Can be used for insert, update or delete.
Example
Processing for aDynamic non-selecstatement thatproduces a unknowresults table
Processing for a Dynamicnon-select statementthat produces a knownresults table
Processing for aDynamic non-selectstatement executedmore than once
Processing for a Dynamic non-select statement executedonce
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 118/150
Declare Cursor
Prepare
Describe
Allocate storage fhost variables
Open
Fetch
close
Declare Cursor
Prepare
Open
Fetch
close
Prepare
Execute
Execute Immediate
Format non-selectstatement in avariable-length strhost variables
Format non-selectstatement in a variable-length string hostvariables
Format non-selectstatement in a variable-length string hostvariables
Format non-select statementin a variable-length stringhost variables
Example
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 119/150
Methods for using Non Select SQL
Prepare And Execute
Execute Immediate
May Or May Not Have Parameter Markers.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 120/150
Prepare
The SQL statement is prepared and assigned a unique label.
A prepared statement can be executed several times in a program
General format
Exec Sql
Execute prepared-statement-name
[using { :host-var[: host-var] Descriptor Sqlda -name}
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 121/150
[using { :host-var[: host-var] Descriptor Sqlda -name}
End-Exec.
________________________________________________________
1. Symbolic name specified on the prepare statement the processed the
prepared statement u want to execute.
2. Cobol host variable whose name will be substituted for a parametermarker in the prepared sql statement.
3. Sqlda-name that contain descriptions of the host variables whose
values are to be substituted for parameter markers in the prepared
statement.
Execute Executes the SQL statement
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 122/150
Execute Immediate
Prepares and executes the SQL statements in one shot.
Syntax.
Fixed - List Select StatementsFixed-list implies that the number 0f columns and the datatypes of those columns are known in
advance.
Number of rows that are returned need not be known
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 123/150
Steps
Declare a cursor for the statement name.
Prepare the statement.
Open the cursor
Fetch rows from result table.
Close the cursor.
Example
Declare Open Fetch Close
Exec Sql
Declare cursor-name for prepared-select-name
End-Exec
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 124/150
End Exec.
________________________________________________________Exec Sql
Open cursor-name using {:host-var… Descriptor sqlda-name}
End-Exec.
________________________________________________________
Exec Sql
Fetch cursor-name Into {:host-var…[:host-structure]}
[using Descriptor sqlda-name]
End-Exec.
Example
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 125/150
Varying List Select
• Returns rows containing an unknown number of values of unknown type. Host variables to be decla
are not known in advance. May or may not have parameter markers
Steps Involved:
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 126/150
Include an SQLCA
• Load the input SQL statement into a data area.
• Prepare and execute the statement
• Include an SQLDA
• Declare a cursor & prepare the variable statement
• Obtain the information about the type and size of each column of the result table
• Open the cursor; Fetch a row
• Eventually close cursor and free main storage
• Handle any errors that may arise.
• SQLDA must be explicitly coded and DB2 does not provide any include file.
TABLE CONTENTS
SYSCOLUMNS Table contains one row for every column of each taband view
SYSRELS Table contains one row for every referential constra
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 127/150
y
SYSFOREIGNKEYS Table contains one row for every column or everyforeign key.
SYSVIEWS Table Contains One or More Row for Each View.
SYSVIEWDEPT Table records the dependencies of views on tables another views.
__________________________________________________________
SELECT NAME, COLTYPE, LENGTH FROM SYSIBM.SYSCOLUMNS
WHERE TBNAME=‘DEPT’ AND TBCREATOR=‘IKSA01’;
SQLDA Format
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 128/150
Performance Considerations for DB2 Programming
General Guidelines
Avoid Numeric conversions
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 129/150
Select only columns that are used
For single row retrieval, SELECT can be used instead of CURSOR processing.
Cursors cannot be used for Update or Delete if DECLARE CURSOR includes any of th
following :
UNION, GROUP BY, HAVING, SUB-QUERIES,DISTINCT, ORDER BY, JOINS
DECLARE CURSOR must precede any other comma (OPEN, FETCH, CLOSE) relating to
cursor.
Initialize Host variables used by the cursor before opening the cursor. Otherwise data integri
problems may arise.
Explicitly close all cursors, to increase performance.
WITH HOLD option is not available for CURSORS coded
in a CICS-DB2 program.
For Update & Delete, use Cursors to improve performance.
For non-cursor Update and Delete statements, always use primary key in the WHERE claus
Avoid SELECT * in Embedded SQL program.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 130/150
p g
Filter data using WHERE clause
Use joins instead of correlated sub select statements.
INDEX Considerations
• Using an INDEX can Save a tablespace scan
Avoid a sort. DB2 decides on use of an INDEX.
A table can have more than one Index on different Columns.
Access paths :Tablespace Scan
Clustered Index Scan, Non-clustered Index Scan.
DB2 & CICS
CICS or ‘Customer Information Control System’ is a database/data communication cont
system. We can access DB2 data from CICS programs. When DB2 data is accessed fr
CICS, multiple threads can be active simultaneously, enabling concurrent access to a D
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 131/150
, p y, g
subsystem by multiple users of a CICS region. A mechanism called CICS Attachment Fac
connects CICS with DB2. Using this facility, each CICS region can be connected to only one D
subsystem at a time. Each subsystem can, however, to be connected to more than one CI
region at a time.
CICS provides an interface to DB2, but DB2 requires its own region independent of the CI
region. Both CICS and DB2 require its own unique regions under the OS. CICS applicat
programs can be issue a set of commands for SQL services in order to access the D
database.
Locks
DB2 allow more than one application to access the same data at essentially same time. This
known as concurrency . To control such undesirable results such as lost updates, access
uncommitted data and unrepeatable reads, concurrency must be controlled. DB2 uses lock
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 132/150
uncommitted data and unrepeatable reads, concurrency must be controlled. DB2 uses lock
control concurrency.
DB2 locks can be compared in four basic aspects: object, size, duration, and mode.
Object of lock is the resource being locked.
Size of lock can be page, table or tablespace
Duration of lock is the length of time the lock is held. It varies according to when the lock
acquired and released. This is controlled by bind options ACQUIRE, RELEASE and ISOLATIO
Mode of lock tells what access to the locked object is permitted to the lock owner and to a
concurrent application processes.
Page Lock modes:
S (SHARE) The lock owner and any concurrent processes can read but not
change the locked page. Concurrent processes can acquire S or U locks on
the page.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 133/150
U (UPDATE) The lock owner can read but not change the locked page; howev
the owner can promote the lock to an X lock and then can change the page
Processes concurrent with the U lock can acquire S locks and read the pag
but no concurrent processes can acquire a U lock.
X (EXCLUSIVE) The lock owner can read or change the locked page.
Concurrent processes cannot acquire any lock on the page nor can they
access the locked page.
Effects of DB2 locks:
The IMS resource lock manager (IRLM) is responsible for managing
requests for locks and controlling access to DB2 databases.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 134/150
Suspension: The IRLM suspends an application process if it requests a lo
on an object that is already owned by another application process and cann
be shared. The suspended process is said to be “Waiting” for the lock. T
process resumes running when the lock is available.
Timeout : Timeout occurs when the application process is suspended for long
than a preset interval. DB2 reports a timeout by returning a SQLCODE of –9
or –913 to the process.
Deadlock: A deadlock occurs when 2 or more application processes each hold lock
resources that the others need and without which they cannot proceed. After the end of t
preset time interval, DB2 can rollback the current unit of work for one of the processes,
request the process to terminate. That frees the locks and allows the remaining processes
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 135/150
continue.
ACQUIRE and RELEASE options:
These options of BIND or REBIND are used to specify when DB2 is to lock the tables
tablespaces and when to release the locks.
ACQUIRE (ALLOCATE)/RELEASE (DEALLOCATE)
This option avoids deadlocks by locking your resource at the beginning. Use this option
processing efficiency is more important than concurrency.
All tables or tablespaces are locked when the plan is allocated and released only when the p
is terminated. This option reduces concurrency.
ACQUIRE (USE)/RELEASE (DEALLOCATE):
The table or tablespace is locked only when it is needed while running. All tables a
tablespaces are unlocked only when the plan terminates.
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 136/150
ACQUIRE(USE)/RELEASE(COMMIT) :
This is the default option & provides greater concurrency. A table or tablespace is locked o
when needed. The lock is released when a SQL COMMIT or ROLLBACK statement is issued
when the application process terminates.
This option can increase the frequency of deadlocks
ACQUIRE(ALLOCATE)/RELEASE(COMMIT)
is not allowed.
ISOLATION option.
This option on BIND or REBIND helps DB2 release S or U page locks as soon as possible. The ISOLATION opt
does not apply to changed data. All changed data remains locked at least until the next commit point. T
ISOLATION option can be either CS or RR
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 137/150
CURSOR STABILITY (CS)
For read only processing, the page lock is held only while the cursor is positioned on that page. When the curs
moves to another page, that lock is released. The application is protected from concurrent updates or deletion
the row it is currently processing.
REPEATABLE READ(RR)
Page locks are held at least until the next commit point. With this option, if the application process returns to
same page and reads the same row again, the data cannot be changed. The application process is assured t
SQL SELECT statements it issues are repeatable.
Use Repeatable Read when your application has to retrieve the same rows several times.
APPENDIX
Common SQL CODES
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 138/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 139/150
Limits Imposed by DB2
Identifier Length Limits
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 140/150
Numeric Limits
String Length Limits
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 141/150
Date Time Limits
DB2 Limits
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 142/150
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 143/150
Exercises
Code and execute CREATE statements to create EMPLOYEE & DEPT Tables.
Table Specifications
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 144/150
Customer Details
Account Details
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 145/150
Using the Basic Select:
Display all the rows and columns from Customer table.
• Display Acc_no,Acc_Type, Name, Balance from Customer table
• List all the information for any account type where Rate_o_int is unknown
• Display the Acc_no, Name , Acc_Type, DOB and Balance of all Customers who have le
th 4000 B l S t th lt b
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 146/150
than 4000 Balance. Sort the results by name.
• List the Accounttypes & MinBal where Rate_o_int is unknown.
• Show Acc_no, name, address and phone no of customers whose accounttype is either CA
SB.
• Produce a list of customers whose name begins with “V”. Sort the list by name.
• Display name, Acc_type & balance. for customers with a balance greater than 10,000.
• Produce a list of customers whose Balance is < 3,000. List the output in descending order
of balance.
Using the Complete Select Statement
Display the sum of all balances along with the company average balance balance, minimum a
maximum balance
• Which customer name comes first alphabetically?
• How many different acctypes do customers have?
Sho the a erage balance for each acc no
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 147/150
• Show the average balance for each acc_no.
• List the average balance for each acc_type where the average balance is greater th
50,00.00
• Display name, Acc_no and acc_type name in all account types whose Acc_type begins w
C.
• Show the average balance for men and the average balance for women for each acc_typ
Identify the acc_type by name. Order the results by descending balances within accou
details.
• Produce a report that gives the no. of customers and total balance for acc_types that be
with “C”, “S” or “F” . List the results in order by acc_type balance.
Using Select Statement with Subqueries
Show the name and acc_type of customers in all phone nos where phone no includes “472”
• Display name and acc_type of customers in all phone nos where phone no includes “472”
• List each acc_type that has an average balance less than banks average balance.
• Display list of all acc_no of female customers and male customers in all acc_type whe
acc type includes "SB"
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 148/150
acc_type includes "SB"
• Write a program to insert data into the customer and account details table after accepting t
required data from the terminal
• Write a program to list all the customersin the bank and write the result to a sequential file
• Write a program to update the account details table by accepting the acc type from t
terminal
Source Program
Modified SourceNon-SQL
DB2 Precompileror Host-
LanguageCompiler
SQL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 149/150
Object Program
Link Edit
Compilation
Load Module
DBRM
Bind PackageDB2 Catalog Bind Plan
Plan
Source Program
Modified SourceNon-SQL
DB2 Precompileror Host-
LanguageCompiler
SQL
8/6/2019 Db2 Application Modified
http://slidepdf.com/reader/full/db2-application-modified 150/150
Object Program
Link Edit
Compilation
Load Module
DBRM
Bind PackageDB2 Catalog Bind Plan
Plan