Table Of Contents


1. PURPOSE AND SCOPE OF THE DOCUMENT....................................1
   1.1. USERS OF THE DOCUMEN...
5.1.3. Create Table.................................................................................51
     5.1.4. Create ...
8.2.2. Referential Integrity Enforcement Rules....................................140
     8.2.3. Example For Referential ...
1.     Purpose and Scope of the Document

The Purpose of this document is to train fresh Software Engineers who would like...
2.    Introduction

DB2 ( IBM DATABASE2 ) is a highly successful relational database management
system. DB2 enables it’s u...
2.1.   Database Management Systems (DBMS)

DATABASE MANAGEMENT SYSTEMS deal with the problem of storing and
retrieving lar...
2.2.        Types Of DBMS

Depending on data models used, database management systems are mainly
divided into three.

    ...
♦ TABLE S represents SUPPLIERS. Each supplier has a unique SUPPLIER
  NUMBER (S#), a SUPPLIER NAME (SNAME), a RATING (STAT...
2.2.2. HIERARCHICAL DBMS

Hierarchical View Of Supplier And Parts Database

In hierarchical database suppliers, parts and ...
2.2.3. Net Work DBMS


              SUPPLIER                                      PART RECORD
             RECORD SET    ...
2.3.   Sample Db2 Database

The sample database consists of THREE tables and these tables are used
through out this book.
...
3.     Structure Of DB2

This chapter deals with the definitions and examples of objects present in
DB2.The topics include...
STRUCTURE OF DB2


        THE ELEMENTS OF DB2 ARE DIVIDED INTO
             TWO BROAD CATEGORIES

        DATA STRUCTURES...
HIERARCHY OF DATA STRUCTURES

  DATABASE D1                    STORAGE GROUP
                                 G1
     TABL...
Hierarchy Of Data structures

♦ The total collection of stored data is divided into a number of disjoint
   databases. The...
DATA BASES
                    DATABASE1




                           TABLESPACE1

        INDEX 1         TABLE 1     T...
DB2 STORAGE GROUPS




         STORAGE GROUP 1



         VOLUME 1      VOLUME 2




♦ USER AND SYSTEM DATABASES ARE PHY...
TABLE SPACES


                TABLESPACE 1


                       TABLE 1

                        TABLE 2




        ...
Table Spaces

A TABLE SPACE can be thought of as a logical address space on secondary
storage that is to hold one or more ...
SIMPLE TABLESPACE


              SIMPLE TABLESPACE

                           FREE
                           PAGE

 FRE...
Simple Tablespace

In simple table space records of tables are interleaved .Records of different tables
may be present in ...
SEGMENTED TABLESPACE




                                           SEGMENT1



                                          ...
Segmented Tablespace

In a SEGMENTED TABLESPACE the tablespace is divided into segments and
each segment consists of a log...
PARTITIONED TABLESPACE



  A—F                                             PARTITION1



  G—P                           ...
Partitioned Tablespace

PARTITIONED TABLESPACES are intended for stored tables that are sufficiently
large. Partitioned ta...
TABLES


                      TABLE S


                KEY             COLUMNS


                 S#    SNAME    STATUS ...
VIEWS



     BASE TABLE AS IT EXISTS        VIEW AS THE PROGRAM’S
     STORAGE                        LOGIC SEES IT.

   ...
Views

A VIEW is a named table that is represented, not by its own physically separate,
distinguishable stored data, but r...
INDEX SPACES

                     INDEX SPACE 1




                          INDEX 1




♦ ONLY ONE INDEX IS STORED IN A...
INDEX



                INDEX 1

                RID       VALUE



                                      PAGE P




    ...
Indexes

An index contains values from one or more of a table’s columns and a pointer to
the record in a data which matche...
ALIASES


♦ AN ALIAS IS AN ALTERNATIVE NAME FOR A TABLE OR VIEW. IT IS A
  QUALIFIED NAME THAT CAN BE USED BY ANY AUTHORIZ...
Aliases

Aliases are useful for creating meaningful names for TABLES and VIEWS.
ALIASES are created using CREATE ALIAS sta...
SYNONYMS


♦ SYNONYMS ARE USEFUL FOR CREATING MORE MEANINGFUL NAME
  FOR A PERSON USING A TABLE OR VIEW

♦ A SYNONYM IS AN...
Synonyms

A SYNONYM like an ALIAS is an alternative name for a table. Creating a
SYNONYM for a table or view will allow th...
DB2 CATALOG



      DB2     CATALOG CONSISTS OF TABLES WHICH    CONTAIN

      INFORMATION ABOUT OBJECTS DEFINED UNDER   ...
DB2 Catalog

The CATALOG in DB2 is a system database that contains information concerning
various objects that are of inte...
DB2 DIRECTORY

         DB2    DIRECTORY    CONTAINS INFORMATION

         REQUIRED   TO START DB2   AND DB2   USES

     ...
ACTIVE AND ARCHIVE LOGS



     DB2 RECORDS ALL DATA CHANGES AND SIGNIFICANT
     EVENTS IN A LOG AS THEY OCCUR

     DB2 ...
BUFFER POOLS



    BUFFER POOLS ARE AREAS OF VIRTUAL

    STORAGE THAT TEMPORARILY STORE PAGES

    OF TABLE SPACES OR IN...
Buffer Pools

Buffer pools, also known as virtual buffer pools, are areas of virtual storage used
temporarily to store pag...
4.     Data Types
This chapter describes various data types used in DB2 and their examples.
COBOL declarations of the corr...
DATA TYPES


     EVERY COLUMN IN A TABLE IS ASSIGNED A SPECIFIC
     TYPE AND SIZE OF DATA

     CATEGORIES OF DATA TYPES...
NUMERIC DATA

SMALLINT :       TWO BYTE BINARY INTEGER , 15 BITS AND SIGN.

INTEGER     :    FOUR BYTE BINARY INTEGER, 31 ...
NULLS


♦ SQL SYSTEMS LIKE DB2 REPRESENT MISSING INFORMATION IN A
  COLUMN BY MEANS OF SPECIAL MARKERS CALLED NULLS.

♦ TH...
Nulls

Null values are used in a table when actual values are unknown. Suppose the
weight of a part in the SUPPLIER-PARTS ...
STRING DATA

CHARACTER FORMAT



CHARACTER(n) : FIXED LENGTH STRING OF n 8 BIT CHARACTERS
               OCCUPYING N BYTES...
GRAPHIC FORMAT


GRAPHIC(n) :   FIXED LENGTH STRING OF N 16 BIT CHARACTERS
               OCCUPYING 2n BYTES


VARGRAPHIC(...
DATE / TIME DATA


          INTERNAL REPRESENTATIONS

          DATE        YYYYMMDD

          TIME        HHMMSS

     ...
Date / Time Data

Columns whose data types are DATE, TIME, OR TIMESTAMP are represented in
an internal form that is transp...
EQUIVALENT COBOL DECLARATIONS OF DATA TYPES


DATATYPE               COBOL DECLARATION


CCTEMP SMALLINT        01 CCTEMP ...
5.   SQL Programming

IN DB2 operations are done using structured query language. This chapter
explains types of SQL and t...
SQL PROGRAMMING

        SQL (STRUCTURED QUERY LANGUAGE ) IS
        THE LANGUAGE USED TO ACCESS DATA
        IN DB2 TABLE...
5.1.   DDL Statements

Data definition language statements used for creating, changing and dropping
DB2 objects. The follo...
CREATE DATABASE



     THE CREATE DATABASE STATEMENT DEFINES A
     DB2 DATABASE TO THE DB2 SUBSYSTEM. THE NAME
     MUST...
CREATE TABLESPACE



     THE CREATE TABLESPACE STATEMENT ALLOCATES SPACE FOR
     TABLES. THIS STATEMENT CREATES A SIMPLE...
Create Table Space

Many parameters can be specified in the CREATE TABLESPACE statement
which decides the type of tablespa...
CREATE TABLE



     CREATE TABLE STATEMENT CREATES A TABLE IN A
     TABLESPACE. TABLE NAME IS UNIQUE FOR A USER.
     IF...
KEYS



     ♦ A KEY IS ONE OR MORE COLUMNS THAT ARE IDENTIFIED AS
       SUCH IN THE DESCRIPTION OF A TABLE, AN INDEX, OR...
PRIMARY KEY


     ♦ A PRIMARY KEY IS A UNIQUE KEY THAT IS A PART OF THE
       DEFINITION OF A TABLE



           P#    ...
FOREIGN KEYS



      ♦ A FOREIGN KEY IS A COLUMN OR COMBINATION OF COLUMNS
        IN ONE TABLE WHOSE VALUES ARE REQUIRED...
CREATE VIEW



          THE CREATE VIEW STATEMENT CREATES A
          VIEW ON TABLES OR VIEWS. IF THE VIEW NAME
         ...
CREATE INDEX



     THE CREATE INDEX STATEMENT CREATES A PARTITIONED
     OR NON PARTITIONED INDEX AND AN INDEX SPACE.
  ...
ALTER TABLE


     THE ALTER TABLE STATEMENT CHANGES THE
     DESCRIPTION OF A TABLE

     TO ADD MULTIPLE COLUMNS ,CODE M...
DROP


                THE DROP STATEMENT DELETES AN OBJECT


                        ALIAS      alias name
              ...
Drop

The results of dropping various objects are given below.

1. Dropping an alias has no effect on any view or synonym ...
5.2.   DML Statements

Data manipulation statements are used for retrieving data from DB2 tables. The
following statements...
DML STATEMENTS

SELECT

                    SQL SELECT

               REQUIRED SEQUENCE
                    SELECT

     ...
COMPARISON OPERATORS


             =    EQUAL

             ^=   NOT EQUAL

             <>   NOT EQUAL

             >  ...
SELECT DISTINCT



       SELECT DISTINCT IS TO ELIMINATE DUPLICATE ROWS

       Q      :   GET PART NUMBERS FOR ALL PARTS...
MULTIPLE CONDITIONS




              MULTIPLE CONDITION RETRIEVAL

                       AND    OR


              Q1 : ...
ORDER BY



         SPECIFY COLUMN NAME AND TELL WHETHER
         ASCENDING OR DESCENDING SEQUENCE

         THE DEFAULT ...
IN, BETWEEN




   IN   :     TO MATCH ONE OF A LIST OF VALUES


   BETWEEN:         TO SELECT A RANGE OF VALUES

        ...
PARTIAL SEARCH




   TO SEARCH ON A SUBSET OF CHARACTERS :     LIKE

   NOT TO SEARCH ON A SUBSET OF CHARACTERS :    NOT ...
RESULT 1
 S#        SNAME   CITY

 S1        SMITH   LONDON
 S4        CLARK   LONDON


RESULT 2

  S#       SNAME   CITY
...
AGGREGATE FUNCTIONS



     COUNT     :    NUMBER OF VALUES IN THE COLUMN

     SUM       :    SUM OF VALUES IN THE COLUMN...
GROUP BY



       WITH GROUP BY, A COLUMN FUNCTION RESULTS
       IN A SINGLE VALUE FOR EACH GROUP



       Q   :       ...
HAVING



    HAVING IS USED TO GET SOME SPECIFIC ROWS, FROM THE ROWS
    OBTAINED BY GROUP BY CLAUSE, WHICH SATISFY THE C...
JOINING TABLES



     IT IS A QUERY IN WHICH DATA IS RETRIEVED FROM MORE
     THAN ONE TABLE

     Q:   GET ALL COMBINATI...
SUB QUERIES



        A SUB QUERY IS A SELECT-FROM-WHERE EXPRESSION
        THAT IS NESTED INSIDE ANOTHER SUCH EXPRESSION...
UNION




   THE RESULTS OF ONE OR MORE RELATIONS ARE
   MIXED TO FORM A SINGLE RELATION USING UNION .

   Q:   GET PART N...
INSERT




      THE INSERT STATEMENT INSERTS A NEW ROW INTO
      THE TABLE. YOU CAN EITHER INSERT VALUES FOR
      ALL C...
UPDATE




      THE UPDATE STATEMENT UPDATES THE VALUES
      OF SPECIFIED COLUMNS IN ROWS OF A TABLE OR
      VIEW. UPDA...
DELETE




    THE DELETE STATEMENT DELETES ROWS FROM
    A TABLE OR VIEW. DELETING A ROW FROM A
    VIEW DELETES THE ROW ...
5.3.   Control Statements

Statements other than DDL and DML are explained in this section. They are


5.3.1. Grant

5.3.2...
CONTROL STATEMENTS

GRANT



     TO PERFORM ANY OPERATION ON ANY OBJECT THE
     USER MUST HOLD THE APPROPRIATE PRIVILEGE...
REVOKE




    USED TO REVOKE PREVIOUSLY GRANTED PRIVILEGES ON AN
    OBJECT FROM USERS. GENERAL FORMAT OF REVOKE IS
    S...
COMMIT




    COMMIT OPERATES ON A UNIT OF RECOVERY

    AFTER EXECUTING THIS STATEMENT

          ♦ ALL CHANGES WILL BE ...
ROLLBACK




    A UNIT OF WORK IS UNDONE IF ANY ABNORMAL

    CONDITION OCCURS . WHEN THIS STATEMENT

    IS EXECUTED

  ...
6.     Program Structure

This section gives an over view of a DB2 application program .Different sections
to be included ...
PROGRAM STRUCTURE
          STRUCTURE OF A PROGRAM THAT ACCESSES DB2


                         SQLCA


               HOS...
Program Structure

Programs that access DB2 are written in a number of host languages - COBOL,
PL/1, C , ASSEMBLER , FORTR...
HOST VARIABLES




     HOST VARIABLES ARE USED TO IDENTIFY THE SYMBOLIC
     NAME OF STORAGE, THAT HAS BEEN DECLARED USIN...
EXAMPLE(1)

♦ SQL STATEMENT 1
    INSERT INTO S
    ( S#, SNAME )
    VALUES ( ‘S6’ , ‘GEORGE’ )

♦ SQL STATEMENT 2
    IN...
DECLARING HOST VARIABLES



THERE ARE TWO METHODS OF HOST VARIABLE DECLARATION


(1) DECLARE HOST VARIABLES IN THE WORKING...
Declaring Host Variables

You can declare all host variables in the working storage section of the COBOL
program. The host...
INDICATOR VARIABLES



     INDICATOR VARIABLE INDICATES THE PRESENCE
          OF NULL VALUE IN A COLUMN


     SELECT SN...
Indicator Variables

When the program is to receive a value from a column that allows nulls, the
program can get either a ...
Examples

1.   EXEC SQL
     SELECT SNAME , CITY
     INTO :SUPNAME:SUPNAMIND , :PGMCITY
     FROM S
     WHERE S# = ‘ S1’...
SQLCA ( SQL COMMUNICATION AREA)



    THE SUCCESS OR FAILURE OF THE LAST EXECUTED SQL
         STATEMENT IS DESCRIBED IN ...
SQLCA

The SQL communication area (SQLCA) is a data structure that must be included
in any host language program using SQL...
COBOL STRUCTURE OF SQLCA


    01 SQLCA.
         05 SQLCAID     PIC X(8).
         05 SQLCABC     PIC S9(9) COMP-4.
     ...
SQLCA RETURN CODES


                     INTEGER      CHAR(1)
     CONDITION       SQLCODE      SQLWARN0        REQUEST
 ...
SQLCA WARNINGS


SQL WARNING        DESCRIPTION


SQLWARN0      THIS FIELD IS BLANK IF ALL SQL WARNINGS
              FROM...
SQLCA WARNINGS…..


SQL WARNING   DESCRIPTION



SQLWARN6      CONTAINS W IF THE ADDITION OF A MONTH OR YEAR
             ...
Important SQL codes

-102 LITERAL STRING IS TOO LONG. STRING BEGINS string

-107 THE NAME name IS TOO LONG. MAXIMUM ALLOWA...
-551 auth-id DOES NOT HAVE THE PRIVILEGE TO PERFORM OPERATION
operation ON OBJECT object-name

-603 A UNIQUE INDEX CANNOT ...
CODING AIDS
WHENEVER STATEMENT


                 EXEC SQL
                 WHENEVER Condition Action
                 END...
Whenever Statement

WHENEVER statements help programmers to avoid checking SQLCODE after
every SQL statement. WHENEVER sta...
INCLUDE STATEMENT



    THE INCLUDE STATEMENT INSERTS DECLARATIONS
          OR CODE INTO A SOURCE PROGRAM.



SOURCE PRO...
USING CURSORS

PROCESSING MULTIPLE ROWS

   QUERY:      SELECT STATUS, CTTY INTO :RANK, :CITY
               FROM S WHERE ...
Processing Multiple Rows

In previous example the result of the query gives multiple rows. But there is no
method to deter...
SELECT WITH FETCH

♦ DEFINE A CURSOR
    EXEC SQL
         DECLARE CURSOR K10 FOR
         SELECT SNAME, CITY             ...
Select With Fetch

DECLARE cursor statement defines a cursor with the specified name with an
associated query as specified...
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
DB2 Reference.doc
Upcoming SlideShare
Loading in …5
×

DB2 Reference.doc

971 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
971
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
70
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

DB2 Reference.doc

  1. 1. Table Of Contents 1. PURPOSE AND SCOPE OF THE DOCUMENT....................................1 1.1. USERS OF THE DOCUMENT.........................................................................1 1.2. ASSOCIATED DOCUMENTS..........................................................................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 ©Case Consult (India) Pvt. Ptd. 03/1998 i DB2 Fundamentals /home/pptfactory/temp/20100719111436/db2-referencedoc1182.doc
  2. 2. 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 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 ©Case Consult (India) Pvt. Ptd. 03/1998 ii DB2 Fundamentals /home/pptfactory/temp/20100719111436/db2-referencedoc1182.doc
  3. 3. 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. CONCURRENCY....................................................................................157 9.2. LOCKING STRATEGY..............................................................................157 9.3. LOCK SIZES AND TYPES........................................................................157 9.4. ACQUIRE RELEASE PARAMETERS.............................................................157 9.5. ISOLATION PARAMETER..........................................................................157 10. DB2I (DB2 INTERACTIVE )..............................................................167 10.1. DB2I..............................................................................................167 10.2. SPUFI............................................................................................167 11. UTILITIES............................................................................................171 11.1. LOAD...............................................................................................171 11.2. RUNSTATS.........................................................................................171 11.3. REORG.............................................................................................171 12. ADVANCED DB2..................................................................................179 12.1. MORE ABOUT INDEXES.......................................................................179 12.1.1. Example Of An Index................................................................179 12.1.2. Clustered Indexes.....................................................................179 12.1.3. Non Clustered Indexes..............................................................179 12.2. SPECIAL REGISTERS............................................................................179 12.3. MORE ABOUT LOCKS.........................................................................179 12.3.1. Modes Of Table And Tablespace Locks....................................179 12.3.2. Modes Of Row And Page Locking............................................179 12.3.3. Lock Mode Compatibility Of Table And Table Space Locks....179 12.3.4. Lockmode Compatibility Of Row And Page Locks...................179 12.4. INVOKING ONLINE UTILITIES................................................................179 ©Case Consult (India) Pvt. Ptd. 03/1998 iii DB2 Fundamentals /home/pptfactory/temp/20100719111436/db2-referencedoc1182.doc
  4. 4. 1. Purpose and Scope of the Document The Purpose of this document is to train fresh Software Engineers who would like to get familiarised with DB2 and as a reference material for application programmers. 1.1. Users of the Document This document is intended for database designers, database application programmers, students and teachers and more generally anyone who wishes to broaden his or her knowledge of the database, DB2. 1.2. Associated Documents No associated documents
  5. 5. 2. Introduction DB2 ( IBM DATABASE2 ) is a highly successful relational database management system. DB2 enables it’s users to create, update and control relational database using STRUCTURED QUERY LANGUAGE (SQL). Designed to meet the needs of small and large business alike, DB2 is available on a number of platforms. we will be dealing with DB2 on MVS. RISC SYSTEM/6000 DB2 FOR DB2 FOR OS/2 AIX DB2 FOR DB2 FOR DB2 FOR HP-UX SOLARIS WINDOWS /NT DB2 FOR SINIX DB2 FOR MVS DB2 FOR OS/400 DB2 FOR VSE & VM
  6. 6. 2.1. Database Management Systems (DBMS) DATABASE MANAGEMENT SYSTEMS deal with the problem of storing and retrieving large amounts of data. DBMS provides an environment to share data among it’s users. Preserving the correctness of data and restoring the database in failure are major concerns for DBMS. DBMS DATABASE APPLICATION PROGRAM QUERY PROCESSOR STORAGE MANAGER DATA ♦ DBMS CONSIST OF DATA, HARDWARE, SOFTWARE AND USERS ♦ BENEFITS OF DBMS ARE • REDUCE REDUNDANCY • AVOID INCONSISTENCY • SHARE DATA • MANIPULATES DATA EFFICIENTLY • FAULT TOLERANT • DATA INDEPENDENCE
  7. 7. 2.2. Types Of DBMS Depending on data models used, database management systems are mainly divided into three. ♦ RELATIONAL DBMS ♦ HIERARCHICAL DBMS ♦ NETWORK DBMS 2.2.1. Relational DBMS DB2 is based on relational data model which was formulated by DR. E.F CODD in 1970. Relational systems have their origin in the mathematical theory of relations. Using relational data model , IBM developed DB2 in 1983. A RELATIONAL SYSTEM IS A SYSTEM IN WHICH ♦ THE DATA IS PERCEIVED BY THE USER AS TABLES ♦ QUERIES ARE USED TO EXTRACT DATA FROM THE DATABASE. ♦ ALL DATA VALUES ARE ATOMIC. ie EVERY ROW AND COLUMN POSITION CONTAINS ONLY ONE DATA VALUE; NEVER A LIST OF VALUES ♦ EXAMPLE OF RELATIONAL DBMS IS DB2 SAMPLE DATABASE FOR COMPARING DIFFERENT DBMS TABLE S TABLE SP S# SNAME STATUS CITY S# P# QTY S1 SMITH 20 LONDON S1 P1 300 S2 JONES 10 PARIS S1 P2 200 S3 BLAKE 30 PARIS S1 P3 400 S2 P1 300 S2 P2 400 TABLE P S3 P2 200 P# PNAME COLOR WEIGHT CITY P1 NUT RED 12 LONDON P2 BOLT GREEN 17 PARIS P3 SCREW BLUE 17 ROME P4 SCREW RED 14 LONDON
  8. 8. ♦ TABLE S represents SUPPLIERS. Each supplier has a unique SUPPLIER NUMBER (S#), a SUPPLIER NAME (SNAME), a RATING (STATUS) and a LOCATION OF THE SUPPLIER (CITY). ♦ TABLE P represents PARTS. Each kind of part has a unique PART NUMBER (P#), a PART NAME (PNAME), a COLOUR (COLOR), a WEIGHT (WEIGHT) and a location where the PART IS STORED (CITY). ♦ TABLE SP represents SHIPMENTS. It connects other two tables. It REPRESENTS a shipment of parts of kind P1 by the supplier called S1 and the shipment quantity. ♦ In a relational data model TABLES are called RELATIONS, ROWS are called TUPLES and COLUMNS are referred as ATTRIBUTES. ♦ In a relational data mode association of ROWS of different TABLES are done using COLUMN VALUES of common columns. ♦ DB2 relates TABLE S and SP using the COLUMN SUPPLIER NUMBER(S#). TABLE P and SP are related using the COMMON attribute PART NUMBER (P#). TABLES S and P are related using COLUMN (CITY)
  9. 9. 2.2.2. HIERARCHICAL DBMS Hierarchical View Of Supplier And Parts Database In hierarchical database suppliers, parts and shipments are different databases SUPPLIERS DATABASE 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
  10. 10. 2.2.3. Net Work DBMS SUPPLIER PART RECORD RECORD SET 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)
  11. 11. 2.3. Sample Db2 Database The sample database consists of THREE tables and these tables are used through out this book. TABLE S TABLE SP S# SNAME STATUS CITY S# P# QTY S1 SMITH 20 LONDON S1 P1 300 S2 JONES 10 PARIS S1 P2 200 S3 BLAKE 30 PARIS S1 P3 400 S4 CLARK 20 LONDON S1 P4 200 S5 ADAMS 30 ATHENS S1 P5 100 S1 P6 100 S2 P1 300 TABLE P S2 P2 400 S3 P2 200 P# PNAME COLOR WEIGHT CITY S4 P2 200 S4 P4 300 P1 NUT RED 12 LONDON S4 P5 400 P2 BOLT GREEN 17 PARIS P3 SCREW BLUE 17 ROME P4 SCREW RED 14 LONDON P5 CAM BLUE 12 PARIS P6 COG RED 19 LONDON ♦ TABLE S represents SUPPLIERS. Each SUPPLIER has a unique SUPPLIER NUMBER (S#), a SUPPLIER NAME (SNAME), a RATING (STATUS) and a location of the SUPPLIER (CITY). PRIMARY KEY IS S#. ♦ TABLE P represents PARTS. Each kind of part has a unique PART NUMBER (P#), a PART NAME (PNAME), a COLOUR (COLOR), a WEIGHT (WEIGHT) and a LOCATION where the PART IS STORED (CITY). PRIMARY KEY IS P# ♦ TABLE SP represents SHIPMENTS .It connects other TWO TABLES .It represents a SHIPMENT of PARTS OF KIND P1 by the SUPPLIER called S1 and the SHIPMENT QUANTITY. For a given SHIPMENT the combination of S# and P# is unique .That is the PRIMARY KEY is the COMBINATION of the above mentioned and the FOREIGN KEYS ARE S# AND P#
  12. 12. 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. Hierarchy Of Data Structures 3.2. Databases 3.3. DB2 Storage Groups 3.4. Table Spaces 3.4.1. Simple Tablespace 3.4.2. Segmented Table Space 3.4.3. Partitioned Table Space 3.5. Tables 3.6. Index Spaces 3.7. Indexes 3.8. Views 3.9. Synonyms 3.10. Aliases 3.11. DB2 Catalog 3.12. DB2 Directory 3.13. Active And Archive Logs 3.14. Buffer Pools
  13. 13. STRUCTURE OF DB2 THE ELEMENTS OF DB2 ARE DIVIDED INTO TWO BROAD CATEGORIES DATA STRUCTURES SYSTEM STRUCTURES ♦ DATA STRUCTURES CONTAIN USER DATA AND ARE ACCESSED UNDER USER’S DIRECTION. ♦ SYSTEM STRUCTURES ARE CONTROLLED AND ACCESSED BY DB2 ♦ DATA STRUCTURES CONSIST OF • DATABASES • DB2 STORAGE GROUPS • TABLE SPACES • TABLES • INDEX SPACES • INDEXES • VIEWS • SYNONYMS • ALIASES ♦ SYSTEM STRUCTURES MAINLY CONSIST OF • DB2 CATALOG • DB2 DIRECTORY • ACTIVE AND ARCHIVE LOGS • BUFFER POOLS
  14. 14. HIERARCHY OF DATA STRUCTURES DATABASE D1 STORAGE GROUP G1 TABLE SPACE S1 TABLE T1 TABLE T2 VOLUME 1 (DASD) INDEX X1 VOLUME 2 (DASD) INDEX X2 TABLE T3 PARTITIONED PART 1 TABLESPACE S2 TABLE T3 STORAGE PART 2 GROUP G2 VOLUME2 (3380) PARTITIONED INDEX X3 PART 1 PARTITIONED INDEX X3 PART 2
  15. 15. Hierarchy Of Data structures ♦ The total collection of stored data is divided into a number of disjoint databases. They are USER DATABASES and SYSTEM DATABASES. ♦ Each database is divided into a number of disjoint ‘spaces’, that is several TABLESPACES and INDEX SPACES. A space is a dynamically extendible collection of PAGES, where PAGE is a block of physical storage. ♦ Each table space contains one or more stored tables. A stored table contains a set of stored records. A given stored table must be wholly contained within a single table space. ♦ Each INDEXSPACE contains exactly one index. A given index must be wholly contained with in a single index space. A given stored table and all of its associated indexes must be wholly contained within a single DATABASE. ♦ Each space (TABLE SPACE or INDEX SPACE) has an associated STORAGE GROUP. When a space needs to be extended, storage is acquired from appropriate storage group.
  16. 16. DATA BASES DATABASE1 TABLESPACE1 INDEX 1 TABLE 1 TABLE 2 INDEX 2 TABLESPACE 2 ♦ DATABASE IS A COLLECTION OF A NUMBER OF TABLE SPACES ALONG WITH A SET OF INDEX SPACES ♦ A STORED TABLE AND ALL OF IT’S ASSOCIATED INDEXES MUST BE IN A SINGLE DATABASE ♦ WHEN YOU CREATE A TABLESPACE OR TABLE AND DO NOT SPECIFY THE DATABASE THE OBJECT WILL BE CREATED IN THE DEFAULT DATABASE DSNDB04
  17. 17. DB2 STORAGE GROUPS STORAGE GROUP 1 VOLUME 1 VOLUME 2 ♦ USER AND SYSTEM DATABASES ARE PHYSICALLY STORED IN THE DATASETS OF SPECIFIED STORAGE GROUPS ♦ STORAGE GROUP IS A SET OF VOLUMES OF DIRECT ACCESS STORAGE DEVICES(DASD). ♦ PARTS OF SINGLE DATABASE CAN BE STORED IN DIFFERENT STORAGE GROUPS ♦ DEFAULT STORAGE GROUP IS SYSDEFLT
  18. 18. TABLE SPACES TABLESPACE 1 TABLE 1 TABLE 2 SIMPLE SEGMENTED PARTITIONED ♦ TABLESPACE IS MADE UP OF ONE OR MORE VSAM LINEAR DATASETS (LDS ), WHERE ONE OR MORE TABLES ARE STORED. ♦ A TABLE SPACE IS DIVIDED INTO 4K OR 32K PAGES. ♦ A PAGE IS A UNIT OF I/O TRANSMISSION. ♦ A PAGE MAY CONTAIN ONE OR MORE ROWS (MAX 127). ♦ A ROW MUST LIE WITHIN A PAGE.
  19. 19. 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.
  20. 20. SIMPLE TABLESPACE SIMPLE TABLESPACE FREE PAGE FREE SPACE 4K PAGE RECORD OF TABLE 1 RECORD OF TABLE 2 ♦ SIMPLE TABLESPACE CONTAINS ONE OR MORE TABLES ♦ RECORDS OF DIFFERENT TABLES ARE STORED IN AN INTERLEAVED MANNER. ♦ IMPROVE ACCESS TIME FOR LOGICALLY RELATED DATA
  21. 21. 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.
  22. 22. SEGMENTED TABLESPACE SEGMENT1 SEGMENT2 4K PAGE SEGMENT3 TABLE SPACE HAVING A SEGMENT SIZE 4 RECORD OF TABLE 1 RECORD OF TABLE 2 ♦ TABLE SPACE IS DIVIDED INTO A NUMBER OF SEGMENTS. ♦ RECORDS OF DIFFERENT STORED TABLES ARE NOT INTERLEAVED IN A SINGLE SEGMENT. ♦ A SEGMENTED TABLE SPACE CAN CONTAIN ONE OR MORE TABLES. ♦ SEQUENTIAL ACCESS TO A PARTICULAR TABLE IS MORE EFFICIENT.
  23. 23. 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 .
  24. 24. PARTITIONED TABLESPACE A—F PARTITION1 G—P PARTITION2 Q—Z PARTITION3 RECORD OF TABLE 1 ♦ A PARTITIONED TABLESPACE CAN CONTAIN ONLY ONE TABLE. ♦ EACH PARTITION CONTAINS A PART OF ONE TABLE. ♦ THE PARTITIONS CAN BE INDEPENDENTLY ASSIGNED TO DIFFERENT STORAGE GROUPS. ♦ IMPROVED DATA AVAILABILITY AND QUERY RESPONSE TIME.
  25. 25. 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.
  26. 26. TABLES TABLE S KEY COLUMNS S# SNAME STATUS CITY ROWS S1 SMITH 20 LONDON S2 JONES 10 PARIS S3 BLAKE 30 PARIS S4 CLARK 20 LONDON S5 ADAMS 30 ATHENS ♦ A RELATIONAL DATABASE STORES DATA IN THE FORM OF TABLES. ♦ TABLE CONSISTS OF A NUMBER OF RECORDS. ♦ RECORD CONTAINS COLUMNS, ROWS, KEYS etc. ♦ EACH RECORD SHOULD BE CONTAINED IN A SINGLE PAGE BUT A TABLE CAN BE SPREAD OVER PAGES.
  27. 27. VIEWS BASE TABLE AS IT EXISTS VIEW AS THE PROGRAM’S STORAGE LOGIC SEES IT. TABLE S VIEW S# SNAME STATUS CITY S# STATUS CITY ♦ A VIEW CAN INCLUDE ALL OR SOME OF THE COLUMNS FROM ONE OR MORE BASE TABLES ♦ VIEWS ARE CREATED FOR BASE TABLES OR VIEWS OR A COMBINATION OF VIEWS AND TABLES. ♦ VIEWS ARE LOGICAL REPRESENTATION OF DATA THAT EXISTS IN BASE TABLES. ♦ VIEWS ARE USED FOR SIMPLICITY AND SECURITY.
  28. 28. 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.
  29. 29. INDEX SPACES INDEX SPACE 1 INDEX 1 ♦ ONLY ONE INDEX IS STORED IN AN INDEX SPACE ♦ INDEX SPACE IS AUTOMATICALLY CREATED WHEN THE CORRESPONDING INDEX IS CREATED. ♦ PAGES IN AN INDEX SPACE ARE 4K BYTES IN SIZE. ♦ INDEX SPACE FOR PARTITIONED TABLESPACE ARE PARTITIONED.
  30. 30. INDEX INDEX 1 RID VALUE PAGE P T ♦ INDEX CONSISTS OF TWO PARTS ,RECORD ID (RID) AND INDEXED VALUE. ♦ A TABLE CAN HAVE ANY NUMBER OF ASSOCIATED INDEXES. ♦ INDEXES ARE USED TO IMPROVE PERFORMANCE AND IN SOME CASES TO ENSURE UNIQUENESS. ♦ IN THE EXAMPLE INDEX IS USED TO FIND A RECORD (T) IN PAGE P. ♦ DB2 DETERMINES WHETHER TO USE AN INDEX OR NOT
  31. 31. Indexes An index contains values from one or more of a table’s 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.
  32. 32. ALIASES ♦ AN ALIAS IS AN ALTERNATIVE NAME FOR A TABLE OR VIEW. IT IS A QUALIFIED NAME THAT CAN BE USED BY ANY AUTHORIZATION ID. ♦ AN ALIAS CAN BE DEFINED FOR A TABLE OR VIEW THAT WAS CREATED BY SOME OTHER USER AND FOR WHICH YOU WOULD OTHERWISE HAVE TO USE A FULLY QUALIFIED NAME ♦ ALIASES WERE DESIGNED FOR A DISTRIBUTED ENVIRONMENT TO AVOID HAVING TO REFERENCE THE LOCATION QUALIFIER OF TABLE OR VIEW ♦ ALIAS IS NOT PRIVATE TO THE CREATOR ♦ AN ALIAS CAN BE DEFINED ON AN UNDEFINED NAME. THAT IS THE OBJECT ON WHICH THE ALIAS IS CREATED NEED NOT BE PRESENT AT THE CREATION TIME
  33. 33. 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 BETA’S ALIAS ZTEST to refer to ALPHA’S SAMPLE table. SELECT * FROM BETA.ZTEST
  34. 34. SYNONYMS ♦ SYNONYMS ARE USEFUL FOR CREATING MORE MEANINGFUL NAME FOR A PERSON USING A TABLE OR VIEW ♦ A SYNONYM IS AN UNQUALIFIED NAME THAT CAN ONLY BE USED BY THE AUTHORIZATION ID THAT CREATED IT. ♦ A SYNONYM IS PRIVATE TO THE USER WHO CREATES IT ♦ SYNONYM CANNOT REFER TO REMOTE TABLE IN A DISTRIBUTED DATA ENVIRONMENT ♦ A SYNONYM CAN ONLY BE DEFINED ON THE NAME OF AN EXISTING TABLE OR VIEW.
  35. 35. 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.
  36. 36. DB2 CATALOG DB2 CATALOG CONSISTS OF TABLES WHICH CONTAIN INFORMATION ABOUT OBJECTS DEFINED UNDER THE DB2 SYSTEM . WHEN A NEW TABLE IS CREATED 4 CATALOG TABLES ARE UPDATED . THEY ARE SYSIBM.SYSTABLES , SYSIBM.SYSCOLUMNS . SYSIBM.SYSTABLESPACE , SYSIBM.SYSTABAUTH ♦ EXAMPLES OF CATALOG TABLES • SYSIBM.SYSTABLES CONTAINS INFORMATION OF A TABLE. WHEN A NEW TABLE IS CREATED DB2 INSERTS ONE ROW INTO THIS CATALOG TABLE. • SYSIBM.SYSCOLUMNS CONTAINS INFORMATION ABOUT THE COLUMNS IN A TABLE. THIS TABLE CONTAINS ONE ROW FOR EVERY COLUMN OF EACH ROW IN A TABLE . • SYSIBM.SYSTABLESPACE CONTAINS INFORMATION OF THE TABLE SPACE CREATED. THIS TABLE CONTAINS ONE ROW FOR EACH TABLESPACE. • SYSIBM.SYSTABAUTH CONTAINS INFORMATION OF THE TABLE NAMES AND AUTHORIZATION ID’s WHICH HAVE PRIVILEGES ON THAT TABLE
  37. 37. 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 it’s 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 index’s 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.
  38. 38. DB2 DIRECTORY DB2 DIRECTORY CONTAINS INFORMATION REQUIRED TO START DB2 AND DB2 USES THE DIRECTORY DURING NORMAL OPERATION. DB2 DIRECTORY CONSISTS OF A SET OF DB2 TABLES STORED IN 5 TABLE SPACES IN SYSTEM DATABASE DSNDB01. ♦ SKELETON CURSOR TABLESPACE (SCT02) CONTAINS PLANS ♦ SKELETON PACKAGE TABLE (SPT01) CONTAINS PACKAGES ♦ LOG RANGE TABLE SPACE (SYSLGRNX) CONTAINS THE RBA (RELATIVE BYTE ADDRESS ) THE LOG DATASET ♦ SYSTEM UTILITIES TABLE SPACE (SYSUTILX) CONTAINS THE INFORMATION ABOUT RUNNING UTILITIES ♦ THE DATABASE DESCRIPTOR TABLE SPACE (DBD01) CONTAINS INTERNAL CONTROL BLOCKS THAT DESCRIBE THE DATABASES EXISTING WITHIN DB2. ♦ CANNOT ACCESS DIRECTORY USING SQL
  39. 39. ACTIVE AND ARCHIVE LOGS DB2 RECORDS ALL DATA CHANGES AND SIGNIFICANT EVENTS IN A LOG AS THEY OCCUR DB2 WRITES EACH LOG RECORD TO A DASD DATA SET CALLED THE ACTIVE LOG. WHEN THE ACTIVE LOG IS FULL, DB2 COPIES THE CONTENTS OF THE ACTIVE LOG TO A DASD CALLED THE ARCHIVE LOG ♦ IN THE CASE OF FAILURE DB2 USES LOGS TO RECOVER DATA. ♦ THE ARCHIVE LOG CAN CONSIST OF UP TO 1000 DATA SETS EACH OF WHICH IS A SEQUENTIAL DATA SET.
  40. 40. BUFFER POOLS BUFFER POOLS ARE AREAS OF VIRTUAL STORAGE THAT TEMPORARILY STORE PAGES OF TABLE SPACES OR INDEXES. THE DATA REMAINS IN THE BUFFER UNTIL DB2 DECIDES TO USE THE SPACE FOR ANOTHER PAGE ♦ BUFFER POOLS HOLD THE MOST FREQUENTLY ACCESSED DATA. ♦ USING BUFFER POOLS IMPROVE PERFORMANCE. ♦ DB2 ALLOWS TO USE 50 BUFFER POOLS THAT CONTAIN 4KB BUFFERS AND 10 BUFFER POOLS THAT CONTAIN 32KB BUFFERS. ♦ 4KB BUFFER POOLS ARE BP0 TO BP49 ♦ 32KB BUFFER POOLS ARE BP32K TO BP32K9
  41. 41. 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.
  42. 42. 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. Equivalent Cobol Declarations Of Data Types
  43. 43. DATA TYPES EVERY COLUMN IN A TABLE IS ASSIGNED A SPECIFIC TYPE AND SIZE OF DATA CATEGORIES OF DATA TYPES NUMERIC DATA STRING DATA DATE / TIME DATA ♦ EACH COLUMN IN A TABLE MUST BE DEFINED ♦ COLUMN DEFINITION MUST INCLUDE THE DATA TYPE AND SIZE ♦ ALL DATA TYPES CAN INCLUDE NULL VALUES.
  44. 44. NUMERIC DATA SMALLINT : TWO BYTE BINARY INTEGER , 15 BITS AND SIGN. INTEGER : FOUR BYTE BINARY INTEGER, 31 BITS AND SIGN. DECIMAL (P,Q): PACKED DECIMAL NUMBER HAVING P DIGITS OF WHICH Q DIGITS ARE AFTER THE ASSUMED DECIMAL POINT FLOAT (M) IF M IS BETWEEN 1 AND 21 THEN IT IS SINGLE REAL PRECISION FLOATING POINT AND IT OCCUPIES FOUR BYTES. IT CAN ALSO BE REFERRED AS REAL FLOAT (M) IF M IS BETWEEN 22 AND 53 THEN IT IS SINGLE FLOAT PRECISION FLOATING POINT AND IT OCCUPIES EIGHT BYTES. IT CAN ALSO BE REFERRED AS 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 5.4E-79 to 7.2E+75. FLOAT 5.4E-79 to 7.2E+75. EXAMPLES OF NUMERIC DATA DECLARATION SPKZ DECIMAL(5, 2) DRU SMALLINT HDNR INTEGER
  45. 45. NULLS ♦ SQL SYSTEMS LIKE DB2 REPRESENT MISSING INFORMATION IN A COLUMN BY MEANS OF SPECIAL MARKERS CALLED NULLS. ♦ THE PRESENCE OF NULL VALUE IN A COLUMN DEPENDS ON THE COLUMN DEFINITION . ♦ THREE OPTIONS, SPECIFIED IN COLUMN DEFINITION WHICH DEAL WITH NULL VALUES ARE • NOT NULL • NULL • NOT NULL WITH DEFAULT ♦ IF A COLUMN IS DECLARED AS NOT NULL THEN DB2 WILL NOT ALLOW NULL VALUES ON THAT COLUMN ♦ WHEN A COLUMN IS DECLARED AS NULL WHICH IS THE DEFAULT, DB2 WILL ALLOW NULL VALUE ON THAT COLUMN ♦ NOT NULL WITH DEFAULT MEANS THAT THE COLUMN IN QUESTION CANNOT CONTAIN NULLS, BUT IT IS STILL LEGAL TO OMIT A VALUE FOR THE COLUMN EXAMPLES SPKZ DECIMAL(5, 2) NULL DRU SMALLINT NOT NULL HDNR INTEGER NOT NULL WITH DEFAULT
  46. 46. 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. ♦ Zero for numeric items ♦ Blanks for fixed length string columns ♦ Empty (zero length string) for varying length string columns ♦ The value of CURRENT DATE or CURRENT TIME or CURRENT TIMESTAMP for variables declared with attributes DATE, TIME or TIMESTAMP.
  47. 47. STRING DATA CHARACTER FORMAT CHARACTER(n) : FIXED LENGTH STRING OF n 8 BIT CHARACTERS OCCUPYING N BYTES VARCHAR(n) : VARYING LENGTH STRING UP TO n 8 BIT CHARACTERS OCCUPYING n+2 BYTES . FIRST TWO BYTES ARE USED FOR STORING THE LENGTH OF THE VARIABLE LONG VARCHAR : VARYING LENGTH CHARACTER STRING WHOSE MAXIMUM LENGTH WILL BE DECIDED BY DB2 RANGE OF VALUES CHARACTER(n) : 1 TO 254 VARCHAR(n) : MUST BE LESS THAN PAGE SIZE (4K) LONG VARCHAR : MAXIMUM LENGTH IS DETERMINED BY THE AMOUNT OF SPACE AVAILABLE IN A PAGE EXAMPLES OF CHARACTER DATA REPRESENTATION SPKZ CHAR (20) NUM VARCHAR (60) VAR LONG VARCHAR
  48. 48. GRAPHIC FORMAT GRAPHIC(n) : FIXED LENGTH STRING OF N 16 BIT CHARACTERS OCCUPYING 2n BYTES VARGRAPHIC(n) : VARYING LENGTH STRING UP TO N 16 BIT CHARACTERS OCCUPYING 2n+2 BYTES . FIRST TWO BYTES ARE USED FOR STORING THE LENGTH OF THE VARIABLE LONG VARGRAPHIC : VARYING LENGTH 16 BIT CHARACTER STRING WHOSE MAXIMUM SIZE WILL BE DECIDED BY DB2 RANGE OF VALUES GRAPHIC(N) : 1 TO 127 VARGRAPHIC(N) : N MUST BE LESS THAN HALF THE PAGE SIZE (2K) LONG VARGRAPHIC: MAXIMUM LENGTH IS DETERMINED BY THE AMOUNT OF SPACE AVAILABLE IN A PAGE EXAMPLES OF GRAPHIC DATA DECLARATIONS TABKOST GRAPHIC (10) TABIDVARGRAPHIC (80) TEMP LONG VARRRAPHIC
  49. 49. DATE / TIME DATA INTERNAL REPRESENTATIONS DATE YYYYMMDD TIME HHMMSS TIMESTAMP YYYYMMDDHHMMSSNNNNNN ♦ DATE IS REPRESENTED AS A SEQUENCE OF EIGHT UNSIGNED PACKED DECIMAL DIGITS OCCUPYING 4 BYTES ♦ TIME IS REPRESENTED AS A SEQUENCE OF SIX UNSIGNED PACKED DECIMAL DIGITS OCCUPYING 3 BYTES ♦ TIMESTAMP IS REPRESENTED AS A SEQUENCE OF 20 UNSIGNED PACKED DECIMAL DIGITS OCCUPYING 10 BYTES EXAMPLES OF DATE TIME DECLARATIONS CCTEMP DATE CCDAT TIME CCSTAMP TIMESTAMP
  50. 50. Date / Time Data Columns whose data types are DATE, TIME, OR TIMESTAMP are represented in an internal form that is transparent to the user of SQL. But DATES, TIMES, AND TIMESTAMPS can also be represented by DATE/TIME strings. These are character string representations of date values. When you retrieve date/time values they must be assigned to properly declared character string variables. When a date or time is assigned to a variable, the string format is determined by a precompiler option or subsystem parameter. When a string representation of a datetime value is used in other operations, it is converted to a datetime value. However, this can be done only if the string representation is compatible with the date / time value Example The ISO date format ‘1987-10-12’ is internally stored in 4 bytes. But you must assign a variable with 10 bytes as host variable for retrieving the above date.
  51. 51. EQUIVALENT COBOL DECLARATIONS OF DATA TYPES DATATYPE COBOL DECLARATION CCTEMP SMALLINT 01 CCTEMP PIC S9(4) COMP. CCTEMP INT 01 CCTEMP PIC S9(9) COMP. CCTEMP DECIMAL(9,3) 01 CCTEMP PIC S9(6)V9(3) COMP-3. CCTEMP FLOAT(21) 01 CCTEMP COMP-1. CCTEMP FLOAT(53) 01 CCTEMP COMP-2. CCTEMP CHAR(10) 01 CCTEMP PIC X(10). CCTEMP VARCHAR(80) 01 CCTEMP 49 VARLEN PIC S9(4) COMP. 49 CCVAR PIC X(80).
  52. 52. 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
  53. 53. SQL PROGRAMMING SQL (STRUCTURED QUERY LANGUAGE ) IS THE LANGUAGE USED TO ACCESS DATA IN DB2 TABLES SQL DDL DML CONTROL STATEMENTS ♦ DDL (DATA DEFINITION LANGUAGE) • CREATE • ALTER • DROP ♦ DML (DATA MANIPULATION LANGUAGE) • SELECT • UPDATE • INSERT • DELETE ♦ CONTROL STATEMENTS • GRANT • REVOKE • COMMIT • ROLLBACK
  54. 54. 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 5.1.4. Create View 5.1.5. Create Index 5.1.6. Alter Table 5.1.7. Drop
  55. 55. CREATE DATABASE THE CREATE DATABASE STATEMENT DEFINES A DB2 DATABASE TO THE DB2 SUBSYSTEM. THE NAME MUST NOT START WITH DSNDB AND MUST NOT IDENTIFY AN EXISTING DATABASE IN THIS STATEMENT YOU CAN SPECIFY THE NAME OF BUFFER POOL AND STORAGE GROUP FOR TABLE SPACES AND INDEXES WITHIN THE DATABASE ♦ IF BUFFER POOL IS NOT SPECIFIED IN THE CREATE DATABASE STATEMENT THEN DEFAULT BUFFER POOL USED IS BP0. ♦ IF STORAGE GROUP IS NOT SPECIFIED IN THE CREATE DATABASE STATEMENT THEN DEFAULT STORAGE GROUP USED IS SYSDEFLT. ♦ EXAMPLE CREATE DATABASE "D2110K" BUFFERPOOL BP2 STOGROUP "SGDB2O";
  56. 56. CREATE TABLESPACE THE CREATE TABLESPACE STATEMENT ALLOCATES SPACE FOR TABLES. THIS STATEMENT CREATES A SIMPLE, SEGMENTED, OR PARTITIONED TABLE SPACE IN THE SPECIFIED DATABASE. IF DATABASE IS NOT SPECIFIED THEN TABLESPACE IS CREATED IN THE DEFAULT DATABASE DSNDB04 ♦ EXAMPLES 1. CREATE TABLESPACE "S110K10" IN "D2110K" USING STOGROUP "SGDB2O" PRIQTY 100 SECQTY 52 FREEPAGE 0 PCTFREE 5 BUFFERPOOL BP0 LOCKSIZE ANY CLOSE NO SEGSIZE 8; 2. CREATE TABLESPACE "S110L40" IN "D2110L" USING STOGROUP "SGDB2O" PRIQTY 100 SECQTY 52 ERASE NO NUMPARTS 16 FREEPAGE 0 PCTFREE 5 BUFFERPOOL BP2 LOCKSIZE PAGE CLOSE NO;
  57. 57. Create Table Space Many parameters can be specified in the CREATE TABLESPACE statement which decides the type of tablespace, the SIZE of VSAM datasets which hold the tables and indexes, the amount and distribution of space left free in the datasets, the amount of data covered by concurrency control locks etc. All of these decisions made during table space creation hold performance implications. If the developer does not specify choices for any of these parameters DB2 will use default values. In the given examples DB2 automatically creates VSAM linear datasets needed for the tablespace within the specified storage group. Each data set will be defined on a volume of the storage group specified in the create tableapace statement. The values specified for PRIQTY and SECQTY determine the primary and secondary allocations for the data set. Erase parameter Indicates whether the DB2-managed data sets for the tablespace are to be erased when they are deleted during the execution of a utility or an SQL statement that drops the table space. ERASE NO does not erase the data sets. ERASE YES erases the data sets. As a security measure, DB2 overwrites all data in the data sets with zeros before they are deleted. FREEPAGE parameter Specifies how often to leave a page of free space when the table space or partition is loaded or reorganized. The default is FREEPAGE 0, leaving no free pages. PCTFREE parameter indicates what percentage of each page to leave as free space when the table is loaded or reorganized. The default is PCTFREE 5. LOCKSIZE parameter Specifies the size of locks used within the table space . For more information please refer chapter 9. NUMPARTS parameter Indicates that the table space will be partitioned and the number of partitions in that tablespace. BUFFERPOOL parameter Identifies the buffer pool to be used for the table space and determines the page size of the table space. CLOSE parameter specifies whether or not the data sets are eligible to be closed when the table space is not being used or the limit on the number of open data sets is reached. CLOSE YES says the dataset is eligible for closing. This is the default. CLOSE NO specifies that the dataset is not eligible for closing. SEGSIZE parameter Indicates that the table space will be segmented and specifies, how many pages are to be assigned to each segment. If SEGSIZE and NUMPARTS parameters are not given, then the table space will be SIMPLE
  58. 58. CREATE TABLE CREATE TABLE STATEMENT CREATES A TABLE IN A TABLESPACE. TABLE NAME IS UNIQUE FOR A USER. IF USERA CREATES TABLEA THEN FULLY QUALIFIED NAME WILL BE USERA.TABLEA. USERA CAN SIMPLY USE THE NAME TABLEA BUT OTHER USERS MUST SPECIFY FULLY QUALIFIED NAME EXAMPLES 1. CREATE TABLE D2110L.SP ( ,S# CHAR(5) NOT NULL ,P# CHAR(6) NOT NULL ,QTY INTEGER NOT NULL ,PRIMARY KEY( S# , P# ) ,FOREIGN KEY ( S# ) REFERENCES S, ,FOREIGN KEY ( P# ) REFERENCES P ) IN D2110L.TABSP (2) CREATE TABLE D2110L.SP LIKE D2110K.TAB IN D2110L.TABSP;
  59. 59. KEYS ♦ A KEY IS ONE OR MORE COLUMNS THAT ARE IDENTIFIED AS SUCH IN THE DESCRIPTION OF A TABLE, AN INDEX, OR A REFERENTIAL CONSTRAINT. S# SNAME STATUS CITY S1 SMITH 20 LONDON S2 JONES 10 PARIS S3 BLAKE 30 PARIS KEY ♦ A KEY IDENTIFIES A ROW OF DATA ♦ A ROW IN ONE TABLE CAN CARRY THE KEY OF ANOTHER TABLE SO KEYS ARE USED FOR RELATING TABLES ♦ A KEY COMPOSED OF MORE THAN ONE COLUMN IS CALLED A COMPOSITE KEY. A COMPOSITE KEY IS AN ORDERED SET OF COLUMNS OF THE SAME TABLE. ♦ A UNIQUE KEY IS A KEY THAT IS CONSTRAINED SO THAT NO TWO OF ITS VALUES ARE EQUAL.
  60. 60. PRIMARY KEY ♦ A PRIMARY KEY IS A UNIQUE KEY THAT IS A PART OF THE DEFINITION OF A TABLE P# PNAME COLOR WEIGHT CITY P1 NUT RED 12 LONDON P2 BOLT GREEN 17 PARIS P3 SCREW BLUE 17 ROME P4 SCREW RED 14 LONDON P5 CAM BLUE 12 PARIS P6 COG RED 19 LONDON PRIMARY KEY ♦ PRIMARY KEY OF A TABLE IS THE UNIQUE IDENTIFIER FOR THAT TABLE ♦ PRIMARY KEY CAN BE COMPOSITE ♦ A TABLE CANNOT HAVE MORE THAN ONE PRIMARY KEY, AND THE COLUMNS OF A PRIMARY KEY CANNOT CONTAIN NULL VALUES. ♦ WHEN A PRIMARY KEY IS DEFINED ON A TABLE, A UNIQUE INDEX MUST BE CREATED ON THAT PRIMARY KEY
  61. 61. FOREIGN KEYS ♦ A FOREIGN KEY IS A COLUMN OR COMBINATION OF COLUMNS IN ONE TABLE WHOSE VALUES ARE REQUIRED TO MATCH VALUES OF THE PRIMARY KEY IN SOME OTHER TABLE. TABLE S TABLE SP S# SNAME STATUS CITY S# P# QTY S1 SMITH 20 LONDON S1 P1 300 S2 JONES 10 PARIS S1 P2 200 S2 P1 300 ….. ……… … …… …. …. ….. PRIMARY KEY IN S FOREIGN KEY IN SP ♦ A FOREIGN KEY VALUE REPRESENTS A REFERENCE TO THE ROW CONTAINING THE MATCHING PRIMARY KEY VALUE. ♦ THE TABLE THAT CONTAINS THE FOREIGN KEY IS KNOWN AS THE DEPENDENT TABLE AND THE TABLE THAT CONTAINS THE PRIMARY KEY IS KNOWN AS THE PARENT TABLE. ♦ EACH VALUE OF A FOREIGN KEY MUST BE WHOLLY NULL OR WHOLLY NON NULL. THAT IS IF FOREIGN KEY IS A COMPOSITE KEY THEN ALL COMPONENTS OF THAT KEY MUST BE NULL OR NON NULL, NOT A MIXTURE.
  62. 62. CREATE VIEW THE CREATE VIEW STATEMENT CREATES A VIEW ON TABLES OR VIEWS. IF THE VIEW NAME IS UNQUALIFIED THEN THE AUTHORIZATION ID IS THE IMPLICIT QUALIFIER BASE TABLE: S S# SNAME STATUS CITY VIEW : GOOD_SUPPLIERS S# STATUS CITY ♦ IF YOU DO NOT SPECIFY A LIST OF COLUMN NAMES, THE COLUMNS OF THE VIEW INHERIT THE NAMES OF THE COLUMNS OF THE RESULT TABLE OF THE SUB SELECT. EXAMPLE CREATE VIEW GOOD_SUPPLIERS AS SELECT S# , STATUS, CITY FROM S WHERE STATUS > 15 ;
  63. 63. CREATE INDEX THE CREATE INDEX STATEMENT CREATES A PARTITIONED OR NON PARTITIONED INDEX AND AN INDEX SPACE. INDEX CAN BE CREATED ON ONE OR MORE COLUMNS. WHEN YOU CREATE UNIQUE INDEX THE KEY CANNOT HAVE DUPLICATE VALUES. UNIQUE INDEX SHOULD BE CREATED FOR A PRIMARY KEY. ♦ EXAMPLES 1. CREATE UNIQUE INDEX D2110K.I11010U1 ON D2110K.S (S#) BUFFERPOOL BP0 USING STOGROUP SGDB2O PRIQTY 40 SECQTY 20 CLOSE NO; 2. CREATE INDEX D2110P.I11010U2 ON D2110N.P (P# DESC) 3. CREATE UNIQUE INDEX D2110L.I11010U3 ON D2110L.SP (S#, P#)
  64. 64. ALTER TABLE THE ALTER TABLE STATEMENT CHANGES THE DESCRIPTION OF A TABLE TO ADD MULTIPLE COLUMNS ,CODE MULTIPLE ALTER STATEMENTS. ADDED COLUMNS MUST ACCEPT NULL OR NOT NULL WITH DEFAULT VALUES THIS COMMAND CANNOT BE USED FOR DELETING A COLUMN PRIMARY AND FOREIGN KEYS CAN BE CREATED AND DROPPED USING THIS COMMAND ♦ EXAMPLES 1. ALTER TABLE D2110.P ADD PRICE SMALLINT; 2. ALTER TABLE D2110K.SP FOREIGN KEY(P#) REFERENCES D2110K.P ON DELETE CASCADE; 3 ALTER TABLE D2110K.P PRIMARY KEY(P#); 4 ALTER TABLE D2110K.S DROP PRIMARY KEY(S#);
  65. 65. DROP THE DROP STATEMENT DELETES AN OBJECT ALIAS alias name DATABASE database name INDEX index name STOGROUP stogroup name DROP SYNONYM synonym name TABLE table name TABLESPACE table space name VIEW view name PACKAGE collection-id.package-id FREE PLAN ♦ WHEN AN OBJECT IS DROPPED ALL OBJECTS THAT ARE DIRECTLY OR INDIRECTLY DEPENDENT ON THAT OBJECT ARE DELETED ♦ THE OBJECT’S DESCRIPTION IS DELETED FROM THE CATALOG TABLE.
  66. 66. 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 ,it’s 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.
  67. 67. 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 5.2.2. Joining Tables 5.2.3. Sub Queries 5.2.4. Union 5.2.5. Insert 5.2.6. Update 5.2.7. Delete
  68. 68. DML STATEMENTS SELECT SQL SELECT REQUIRED SEQUENCE SELECT FROM WHERE ORDER BY EXAMPLE Q: GET SUPPLIER NUMBERS AND STATUS FOR SUPPLIERS IN PARIS, IN DESCENDING ORDER OF STATUS 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 30 S2 10
  69. 69. COMPARISON OPERATORS = EQUAL ^= NOT EQUAL <> NOT EQUAL > GREATER THAN ^> NOT GREATER THAN >= GREATER THAN OR EQUAL < LESS THAN ^< NOT LESS THAN <= LESS THAN OR EQUAL
  70. 70. SELECT DISTINCT SELECT DISTINCT IS TO ELIMINATE DUPLICATE ROWS Q : GET PART NUMBERS FOR ALL PARTS SUPPLIED WITH REDUNDANT DUPLICATES ELIMINATED QUERY : SELECT DISTINCT P# FROM SP; RESULT P# P1 P2 P3 P4 P5 P6
  71. 71. MULTIPLE CONDITIONS MULTIPLE CONDITION RETRIEVAL AND OR Q1 : GET SUPPLIER NUMBERS AND SUPPLIER NAMES OF SUPPLIERS LOCATED IN LONDON AND HAVING STATUS CODE 20 Q2 : GET SUPPLIER NUMBERS AND SUPPLIER NAMES OF SUPPLIERS WHOSE STATUS IS 10 OR 20. QUERY 1 : SELECT S#, SNAME FROM S WHERE STATUS = 20 AND CITY = ‘LONDON’ ; QUERY 2 : SELECT S#, SNAME FROM S WHERE STATUS = 10 OR STATUS = 20 ; RESULT 1 RESULT 2 S# SNAME S# SNAME S1 SMITH S1 SMITH S4 CLARK S2 JONES S4 CLARK
  72. 72. ORDER BY SPECIFY COLUMN NAME AND TELL WHETHER ASCENDING OR DESCENDING SEQUENCE THE DEFAULT SEQUENCE IS ASCENDING QUERY: SELECT P# , ‘ WEIGHT IN GRAMS = ’ , WEIGHT * 454 FROM P ORDER BY 3, P# ; RESULT P# P1 WEIGHT IN GRAMS = 5448 P5 WEIGHT IN GRAMS = 5448 P4 WEIGHT IN GRAMS = 6356 P2 WEIGHT IN GRAMS = 7718 P3 WEIGHT IN GRAMS = 7718 P6 WEIGHT IN GRAMS = 8448
  73. 73. IN, BETWEEN IN : TO MATCH ONE OF A LIST OF VALUES BETWEEN: TO SELECT A RANGE OF VALUES CAN USE NOT IN AND NOT BETWEEN Q1 : GET PART NUMBERS , PNAME AND WEIGHT OF PARTS WHOSE WEIGHT IS ANY ONE OF THE FOLLOWING: 12 ,16 ,17 Q2 : GET PART NUMBERS , PNAME AND WEIGHT OF PARTS WHOSE WEIGHT IS IN THE RANGE 16 TO 19 INCLUSIVE QUERY 1 SELECT P# , PNAME , WEIGHT FROM P WHERE WEIGHT IN ( 12 , 16 , 17 ) ; QUERY 2 SELECT P# , PNAME , WEIGHT FROM P WHERE WEIGHT BETWEEN 16 AND 19 ; RESULT 1 RESULT 2 P# PNAME WEIGHT P# PNAME WEIGHT P1 NUT 12 P2 BOLT 17 P2 BOLT 17 P3 SCREW 17 P3 SCREW 17 P6 COG 19 P5 CAM 12
  74. 74. PARTIAL SEARCH TO SEARCH ON A SUBSET OF CHARACTERS : LIKE NOT TO SEARCH ON A SUBSET OF CHARACTERS : NOT LIKE QUERY 1 : SELECT S# , SNAME , CITY FROM S WHERE CITY LIKE ‘L%’ ; QUERY 2 : SELECT S# , SNAME , CITY FROM S WHERE SNAME LIKE ‘%S’ ; QUERY 3 : SELECT S# , SNAME , CITY FROM S WHERE CITY NOT LIKE ‘%A%’ ; QUERY 4 : SELECT S# , SNAME , CITY FROM S WHERE CITY LIKE ‘%DON’ ; QUERY 5 : SELECT S# , SNAME , CITY FROM S WHERE SNAME LIKE ‘_L%’ ;
  75. 75. RESULT 1 S# SNAME CITY S1 SMITH LONDON S4 CLARK LONDON RESULT 2 S# SNAME CITY S2 JONES PARIS S5 ADAMS ATHENS RESULT 3 S# SNAME CITY S1 SMITH LONDON S4 CLARK LONDON RESULT 4 S# SNAME CITY S1 SMITH LONDON S4 CLARK LONDON RESULT 5 S# SNAME CITY S3 BLAKE PARIS S4 CLARK LONDON
  76. 76. AGGREGATE FUNCTIONS COUNT : NUMBER OF VALUES IN THE COLUMN SUM : SUM OF VALUES IN THE COLUMN AVG : AVERAGE OF VALUES IN THE COLUMN MAX : MAXIMUM OF VALUES IN THE COLUMN MIN : MINIMUM OF VALUES IN THE COLUMN Q1 : GET THE TOTAL NUMBER OF SUPPLIERS. Q2 : GET THE TOTAL QUANTITY, AVERAGE QUANTITY, MAXIMUM QUANTITY AND MINIMUM QUANTITY OF PART P2 SUPPLIED QUERY 1 : SELECT COUNT(*) FROM S; QUERY 2 : SELECT SUM (QTY) , AVG (QTY) , MAX (QTY) , MIN (QTY) FROM SP WHERE P# = ‘P2’ ; RESULT 1 RESULT 2 5 1000 250 400 200
  77. 77. GROUP BY WITH GROUP BY, A COLUMN FUNCTION RESULTS IN A SINGLE VALUE FOR EACH GROUP Q : FOR EACH PART SUPPLIED GET THE PART NUMBER AND THE TOTAL SHIPMENT QUANTITY FOR THAT PART QUERY : SELECT P# , SUM (QTY) FROM SP GROUP BY P# ; RESULT P# P1 600 P2 1000 P3 400 P4 500 P5 500 P6 100
  78. 78. HAVING HAVING IS USED TO GET SOME SPECIFIC ROWS, FROM THE ROWS OBTAINED BY GROUP BY CLAUSE, WHICH SATISFY THE CONDITION GIVEN IN THE HAVING CLAUSE. HAVING IS USED TO ELIMINATE GROUPS JUST AS WHERE IS USED TO ELIMINATE ROWS. Q: GET PART NUMBERS FOR ALL PARTS SUPPLIED BY MORE THAN ONE SUPPLIER QUERY : SELECT P# FROM SP GROUP BY P# HAVING COUNT (*) > 1. RESULT P# P1 P2 P4 P5
  79. 79. JOINING TABLES IT IS A QUERY IN WHICH DATA IS RETRIEVED FROM MORE THAN ONE TABLE Q: GET ALL COMBINATIONS OF SUPPLIER AND PART INFORMATION SUCH THAT THE SUPPLIER CITY FOLLOWS THE PART CITY IN ALPHABETICAL ORDER QUERY : SELECT S.* , P.* FROM S , P WHERE S.CITY > P.CITY RESULT S# SNAME STATUS S.CITY P# PNAME COLOR WEIGHT P.CITY S2 JONES 10 PARIS P1 NUT RED 12 LONDON S2 JONES 10 PARIS P4 SCREW RED 14 LONDON S2 JONES 10 PARIS P6 COG RED 19 LONDON S3 BLAKE 30 PARIS P1 NUT RED 12 LONDON S3 BLAKE 30 PARIS P4 SCREW RED 14 LONDON S3 BLAKE 30 PARIS P6 COG RED 19 LONDON
  80. 80. SUB QUERIES A SUB QUERY IS A SELECT-FROM-WHERE EXPRESSION THAT IS NESTED INSIDE ANOTHER SUCH EXPRESSION MAXIMUM 15 LEVELS ARE POSSIBLE IN A NESTED SUB SELECT Q: GET SUPPLIER NAMES FOR SUPPLIERS WHO SUPPLY PART P2. QUERY : SELECT SNAME FROM S WHERE S# IN ( SELECT S# FROM SP WHERE P# = ‘P2’ ) ; RESULT SNAME SMITH JONES BLAKE CLARK
  81. 81. UNION THE RESULTS OF ONE OR MORE RELATIONS ARE MIXED TO FORM A SINGLE RELATION USING UNION . Q: GET PART NUMBERS FOR PARTS THAT EITHER WEIGH MORE THAN 16 POUNDS OR ARE SUPPLIED BY SUPPLIER S2 QUERY : SELECT P# FROM P WHERE WEIGHT > 16 UNION SELECT P# FROM SP WHERE S# = ‘S2’ ; RESULT P1 P2 P3 P6
  82. 82. INSERT THE INSERT STATEMENT INSERTS A NEW ROW INTO THE TABLE. YOU CAN EITHER INSERT VALUES FOR ALL COLUMNS OR OMIT VALUES. BUT OMITTING A A VALUE FOR SOME COLUMN DEPENDS ON THE WAY THE COLUMN WAS DEFINED Q1 : ADD PART P8 (A SPROCKET , COLOR PINK , WEIGHT 14 , CITY NICE ) TO TABLE P Q2 : ADD PART P7 (CITY ATHENS , WEIGHT 24 ) NAME AND COLOR AT PRESENT UNKNOWN. ASSUME THAT THE COLUMNS PNAME AND COLOR ARE CREATED WITH NULL ATTRIBUTE SPECIFICATION. QUERY 1 : INSERT INTO P VALUES ( ‘P8’, ‘SPROCKET’, ‘PINK’, 14, ‘NICE’ ) ; QUERY 2 : INSERT INTO P ( P#, CITY, WEIGHT ) VALUES ( ‘P7’, ‘ATHENS’, 24 ); P# PNAME COLOR WEIGHT CITY … …. … .... ……. P8 SPROCKET PINK 14 NICE RESULT 1 P7 ? ? 24 ATHENS RESULT 2
  83. 83. UPDATE THE UPDATE STATEMENT UPDATES THE VALUES OF SPECIFIED COLUMNS IN ROWS OF A TABLE OR VIEW. UPDATING A ROW OF A VIEW UPDATES A ROW OF THE TABLE ON WHICH THE VIEW IS BASED. Q: CHANGE THE COLOR OF PART P1 TO YELLOW , INCREASE IT’S WEIGHT BY 5 , AND SET IT’S CITY TO UNKNOWN. ASSUME THAT THE DEFINITION OF P.CITY ALLOWS NULL VALUES. QUERY : UPDATE P SET COLOR = ‘YELLOW’ , WEIGHT = WEIGHT + 5 CITY = NULL WHERE P# = ‘P1’ ; RESULT P# PNAME COLOR WEIGHT CITY … … … … … P1 NUT YELLOW 17 ? … … … … …
  84. 84. DELETE THE DELETE STATEMENT DELETES ROWS FROM A TABLE OR VIEW. DELETING A ROW FROM A VIEW DELETES THE ROW FROM THE TABLE ON WHICH THE VIEW IS BASED. SINGLE ROW DELETE Q1: DELETE SUPPLIER S5 MULTIPLE ROW DELETE Q2 : DELETE ALL SHIPMENTS WITH QUANTITY GREATER THAN 300 QUERY 1 : DELETE FROM S WHERE S# = ‘S5’ ; QUERY 2 : DELETE FROM SP WHERE QTY > 300 ;
  85. 85. 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
  86. 86. CONTROL STATEMENTS GRANT TO PERFORM ANY OPERATION ON ANY OBJECT THE USER MUST HOLD THE APPROPRIATE PRIVILEGE FOR THE OPERATION AND THE OBJECT IN QUESTION . THE GRANT STATEMENT GRANTS PRIVILEGES ON AN OBJECT TO AUTHORIZATION IDS. 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 ; PACKAGE AND PLAN PRIVILEGES GRANT EXECUTE ON PLAN PLANB TO CHARLY ; 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 GRANT CREATEDBC TO ARNOLD ;
  87. 87. REVOKE USED TO REVOKE PREVIOUSLY GRANTED PRIVILEGES ON AN OBJECT FROM USERS. GENERAL FORMAT OF REVOKE IS SIMILAR TO THAT OF GRANT. REVOKE CAN BE USED TO REVOKE ALL PRIVILEGES EXPLAINED IN THE GRANT COMMAND EXAMPLES REVOKE SELECT ON TABLE S FROM CHARLY ; REVOKE UPDATE ON TABLE S FROM JOHN ; REVOKE CREATETAB ON DATABASE DBX FROM NANCY ;
  88. 88. COMMIT COMMIT OPERATES ON A UNIT OF RECOVERY AFTER EXECUTING THIS STATEMENT ♦ ALL CHANGES WILL BE DONE PERMANENTLY ♦ ROW LOCKS WILL BE RELEASED ♦ DEFAULT COMMIT IS AT PROGRAM TERMINATION ♦ IF AN APPLICATION DETERMINES THAT A UNIT OF WORK IS SUCCESSFUL IT CAN INDICATE THAT TO THE DATABASE MANAGER VIA A COMMIT. THE DATABASE MANAGER CAN MAKE THE CHANGES PERMANENT ♦ CURSORS ARE CLOSED EXCEPT THOSE DECLARED WITH HOLD OPTION EXAMPLE UPDATE TABLE S SET STATUS = 20 WHERE S# = S1; COMMIT;
  89. 89. ROLLBACK A UNIT OF WORK IS UNDONE IF ANY ABNORMAL CONDITION OCCURS . WHEN THIS STATEMENT IS EXECUTED ♦ ALL CHANGES IN THAT UNIT OF WORK WILL BE BACKED OUT ♦ ALL LOCKS ARE RELEASED ♦ ALL OPEN CURSORS ARE CLOSED ♦ WHEN YOU ISSUE A ROLLBACK THEN THE DATABASE MANAGER WILL RE-ESTABLISH THE STATE OF THE DATABASE AT THE LAST COMPLETED UNIT OF WORK ♦ ROLLBACK WILL BE DONE EITHER BY THE PROGRAM OR BY THE SYSTEM. EXAMPLE ROLLBACK WORK ;
  90. 90. 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 6.1.1. Declaring Host Variables 6.2. Indicator Variables 6.3. SQLCA 6.4. Cobol Structure Of SQLCA 6.5. SQLCA Return Codes 6.6. SQLCA Warnings 6.7. Important SQL codes 6.8. Static SQL 6.9. Dynamic SQL 6.10. Example For A DB2 Application Program
  91. 91. 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 ♦ DIFFERENT SECTIONS TO BE INCLUDED IN A DB2 PROGRAM ARE SHOWN IN THE ABOVE FIGURE. ♦ IF THE HOST LANGUAGE IS COBOL, THEN HOST VARIABLE DECLARATION, SQLCA, AND DECLARE TABLE STATEMENTS SHOULD BE IN THE WORKING STORAGE SECTION AND CURSOR DECLARATIONS SHOULD BE JUST ABOVE THE PROCEDURE DIVISION. ALL OTHER SECTIONS ARE IN PROCEDURE DIVISION.
  92. 92. 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.
  93. 93. HOST VARIABLES HOST VARIABLES ARE USED TO IDENTIFY THE SYMBOLIC NAME OF STORAGE, THAT HAS BEEN DECLARED USING THE APPLICATION PROGRAM LANGUAGE DEFINITION STATEMENT SQL STATEMENT SELECT SNAME INTO :TMPNAME WHERE S# = ‘S1’ HOST VARIABLE ♦ HOST VARIABLES ARE OPTIONAL ♦ HOST LANGUAGE VARIABLES IN SQL STATEMENT MUST BE PRECEDED BY A COLON ♦ HOST VARIABLE MUST MATCH COLUMN DATA TYPE ♦ CAN BE USED ANYWHERE A VALUE IS REQUIRED IN AN SQL STATEMENT
  94. 94. 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 program’s 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 .
  95. 95. DECLARING HOST VARIABLES THERE ARE TWO METHODS OF HOST VARIABLE DECLARATION (1) DECLARE HOST VARIABLES IN THE WORKING STORAGE SECTION (2) EXEC SQL INCLUDE (member name which contains all host variable declarations and declare table statements) END EXEC.
  96. 96. Declaring Host Variables You can declare all host variables in the working storage section of the COBOL program. The host variable declaration should match with the corresponding column definition The host variable names must not begin with SQL or EXEC. Another method of declaring host variables is using the verb INCLUDE. All the host variables are declared in a partitioned dataset member and that member is included in the source program using verb INCLUDE.
  97. 97. INDICATOR VARIABLES INDICATOR VARIABLE INDICATES THE PRESENCE OF NULL VALUE IN A COLUMN SELECT SNAME INTO :SUPNAME:SUPNAMIND FROM S HOST VARIABLE INDICATOR VARIABLE ♦ INDICATOR VARIABLE IS REQUIRED IF THE SELECTED COLUMNS ALLOWS NULL ♦ IF COLUMN CONTAINS NULL VALUE THEN THE INDICATOR VARIABLE IS SET TO NEGATIVE VALUE, HOST VARIABLE IS UNTOUCHED ♦ INDICATOR VARIABLE IS ASSOCIATED WITH A HOST VARIABLE
  98. 98. 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.
  99. 99. 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.
  100. 100. SQLCA ( SQL COMMUNICATION AREA) THE SUCCESS OR FAILURE OF THE LAST EXECUTED SQL STATEMENT IS DESCRIBED IN SQLCA PROGRAM STATUS OF EXECUTED SQL SQLCA SQL STATEMENTS DB2 ♦ AFTER EACH SQL STATEMENT, SQLCA CODES MUST BE CHECKED BY THE PROGRAM TO FIND WHETHER THE SQL WAS SUCCESSFUL OR NOT ♦ SQLCA IS INCORPORATED IN THE PROGRAM USING INCLUDE STATEMENT.
  101. 101. 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 it’s 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.
  102. 102. COBOL STRUCTURE OF SQLCA 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 SQLERRP PIC 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). ♦ MOST IMPORTANT SQLCA CODES ARE SQLCODE AND SQLWARN0
  103. 103. SQLCA RETURN CODES INTEGER CHAR(1) CONDITION SQLCODE SQLWARN0 REQUEST STATUS ERROR <0 FAILED WARNING >0 & <>100 OR ‘W’ SATISFIED WITH SPECIAL CONDITION NOT FOUND +100 DATA NOT FOUND SUCCESS 0 AND ‘ ‘ SUCCESS ♦ IF SQLCODE CONTAINS A NEGATIVE VALUE THEN IT IS AN ERROR ♦ ALL POSITIVE SQLCODES NOT EQUAL TO 100 ARE CONSIDERED WARNINGS ♦ A ‘W’ IN SQLWRN0 INDICATES A WARNING EVEN IF SQLCODE = 0.
  104. 104. SQLCA WARNINGS SQL WARNING DESCRIPTION SQLWARN0 THIS FIELD IS BLANK IF ALL SQL WARNINGS FROM SQLWARN1 TO SQLWARNA ARE BLANKS. CONTAINS ‘W’ IF ONE OR MORE SQL WARNINGS CONTAINS W. SQLWARN1 CONTAINS W IF THE VALUE OF A STRING COLUMN WAS TRUNCATED WHEN ASSIGNED TO HOST VARIABLE. SQLWARN2 CONTAINS W IF NULL VALUES WERE ELIMINATED FROM THE ARGUMENT OF A COLUMN FUNCTION SQLWARN3 CONTAINS W IF THE NUMBER OF RESULT COLUMNS IS LARGER THAN THE NUMBER OF HOST VARIABLES. SQLWARN4 CONTAINS W IF A PREPARED UPDATE OR DELETE STATEMENT DOES NOT INCLUDE A WHERE CLAUSE. SQLWARN5 CONTAINS W IF THE SQL STATEMENT WAS NOT EXECUTED BECAUSE IT IS NOT A VALID SQL STATEMENT IN DB2 FOR MVS/ESA.
  105. 105. SQLCA WARNINGS….. SQL WARNING DESCRIPTION SQLWARN6 CONTAINS W IF THE ADDITION OF A MONTH OR YEAR DURATION TO A DATE OR TIMESTAMP VALUE RESULTS IN AN INVALID DAY. AN INVALID DAY (FOR EXAMPLE, JUNE 31). INDICATES THAT THE VALUE OF THE DAY WAS CHANGED TO THE LAST DAY OF THE MONTH TO MAKE THE RESULT VALID. SQLWARN7 CONTAINS A W IF ONE OR MORE NON ZERO DIGITS WERE LIMITED FROM THE FRACTIONAL PART OF A NUMBER USED AS THE OPERAND OF A DECIMAL MULTIPLY OR DIVIDE OPERATION. SQLWARN8 CONTAINS A W IF A CHARACTER THAT COULD NOT BE CONVERTED WAS REPLACED WITH A SUBSTITUTE CHARACTER. SQLWARN9 CONTAINS A W IF ARITHMETIC EXCEPTIONS WERE IGNORED DURING COUNT DISTINCT PROCESSING. SQLWARNA CONTAINS A W IF AT LEAST ONE CHARACTER FIELD OF THE SQLCA OR THE SQLDA NAMES OR LABELS IS INVALID DUE TO A CHARACTER CONVERSION ERROR.
  106. 106. Important SQL codes -102 LITERAL STRING IS TOO LONG. STRING BEGINS string -107 THE NAME name IS TOO LONG. MAXIMUM ALLOWABLE SIZE IS size -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 name IS AN UNDEFINED NAME -205 column-name IS NOT A COLUMN OF TABLE table-name -303 A VALUE CANNOT BE ASSIGNED TO OUTPUT HOST VARIABLE NUMBER position-number BECAUSE THE DATA TYPES ARE NOT COMPARABLE -401 THE OPERANDS OF AN ARITHMETIC OR COMPARISON OPERATION ARE NOT COMPARABLE -407 AN UPDATE OR INSERT VALUE IS NULL, BUT THE OBJECT COLUMN column-name CANNOT CONTAIN NULL VALUES -501 THE CURSOR IDENTIFIED IN A FETCH OR CLOSE STATEMENT IS NOT OPEN -502 THE CURSOR IDENTIFIED IN AN OPEN STATEMENT IS ALREADY OPEN -503 A COLUMN CANNOT BE UPDATED BECAUSE IT IS NOT IDENTIFIED IN THE UPDATE CLAUSE OF THE SELECT STATEMENT OF THE CURSOR -504 THE CURSOR NAME cursor-name IS NOT DEFINED -540 THE DEFINITION OF TABLE table-name IS INCOMPLETE BECAUSE IT LACKS A PRIMARY INDEX OR A REQUIRED UNIQUE INDEX
  107. 107. -551 auth-id DOES NOT HAVE THE PRIVILEGE TO PERFORM OPERATION operation ON OBJECT object-name -603 A UNIQUE INDEX CANNOT BE CREATED BECAUSE THE TABLE CONTAINS ROWS WHICH ARE DUPLICATES WITH RESPECT TO THE VALUES OF THE IDENTIFIED COLUMNS -623 A CLUSTERING INDEX ALREADY EXISTS ON TABLE table-name -661 INDEX index-name CANNOT BE CREATED ON PARTITIONED TABLE SPACE tspace-name BECAUSE THE NUMBER OF PART SPECIFICATIONS IS NOT EQUAL TO THE NUMBER OF PARTITIONS OF THE TABLE SPACE -672 OPERATION DROP NOT ALLOWED ON TABLE table_name -719 BIND ADD ERROR USING auth-id AUTHORITY PACKAGE package-name ALREADY EXISTS -805 DBRM or PACKAGE NAME location-name.collection-id.dbrm- name.consistency -token NOT FOUND IN PLAN plan-name. REASON reason -811 THE RESULT OF AN EMBEDDED SELECT STATEMENT IS A TABLE OF MORE THAN ONE ROW, OR THE RESULT OF THE SUBQUERY OF A BASIC PREDICATE IS MORE THAN ONE VALUE -904 UNSUCCESSFUL EXECUTION CAUSED BY AN UNAVAILABLE RESOURCE. REASON reason-code, TYPE OF RESOURCE resource-type, AND RESOURCE NAME resource-name -911 THE CURRENT UNIT OF WORK HAS BEEN ROLLED BACK DUE TO DEADLOCK OR TIMEOUT. REASON reason-code, TYPE OF RESOURCE resource-type, AND RESOURCE NAME resource-name -913 UNSUCCESSFUL EXECUTION CAUSED BY DEADLOCK OR TIMEOUT. REASON CODE reason-code, TYPE OF RESOURCE resource-type, AND RESOURCE NAME resource-name
  108. 108. 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 ♦ PHYSICAL PLACEMENT OF WHENEVER STATEMENT DETERMINES THE SQL STATEMENTS UNDER IT’S EFFECT ♦ THE USE OF COLON BEFORE THE LABEL IS OPTIONAL ♦ ‘’ GO TO ‘’ AND ‘’ GOTO ’’ ARE EQUIVALENT
  109. 109. 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
  110. 110. INCLUDE STATEMENT THE INCLUDE STATEMENT INSERTS DECLARATIONS OR CODE INTO A SOURCE PROGRAM. SOURCE PROGRAM SQLCA (TO BE INCLUDED IN SOURCE PROGRAM ) 01SQLCA EXEC SQL 05 SQLCAID PIC X(8). 05 SQLCABC PIC S9(9) COMP-4. INCLUDE SQLCA END-EXEC. ♦ THE INCLUDE STATEMENT INSERTS SOURCE CODE INTO A SOURCE PROGRAM AT PRE COMPILE TIME. ♦ THE INCLUDE STATEMENT CANNOT REFER TO SOURCE STATEMENTS THAT THEMSELVES CONTAIN INCLUDE STATEMENTS.
  111. 111. USING CURSORS PROCESSING MULTIPLE ROWS QUERY: SELECT STATUS, CTTY INTO :RANK, :CITY FROM S WHERE STATUS < 30 ; STATUS CITY 2 LONDON 10 PARIS 20 LONDON RANK CITY STATUS CITY 20 LONDON 10 PARIS 20 LONDON RANK CITY STATUS CITY 20 LONDON 10 PARIS 20 LONDON RANK CITY
  112. 112. Processing Multiple Rows In previous example the result of the query gives multiple rows. But there is no method to determine the number of rows satisfying the condition before actually receiving data from DB2.Therefore it is not possible to allocate storage in the application program to receive an entire set of data. When we are using host variables for retrieving data and if the result is a single row the query will work and SQL return code will be set to zero. But in the given example the result of the query gives multiple rows and the host language can deal with only at a time Now the program is in error, SQLCODE will be set to a negative value and the values of the host variables will be unpredictable. DB2 provides the use of cursors to process SETS of data. The cursor is used to retrieve all rows in the SET one by one. Each fetch of the cursor retrieves the next row in the set of data that meets the condition.
  113. 113. SELECT WITH FETCH ♦ DEFINE A CURSOR EXEC SQL DECLARE CURSOR K10 FOR SELECT SNAME, CITY DEFINITION FROM S WHERE STATUS < 30 END-EXEC ♦ OPEN THE CURSOR EXEC SQL OPEN K10 END-EXEC ♦ FETCH RESULT ROWS ONE AT A TIME EXEC SQL EXECUTION FETCH K10 INTO :SUPNAME, :CITY END-EXEC ♦ CLOSE CURSOR WHEN FINISHED EXEC SQL CLOSE K10 END-EXEC ♦ THE DECLARE CURSOR STATEMENT RELATES A CURSOR TO A SELECT STATEMENT ♦ OPEN CURSOR STATEMENT GENERATES EXECUTABLE CODE. ♦ FETCH CURSOR STATEMENT RETRIEVES A ROW FROM A SET OF DATA ♦ CLOSE CURSOR STATEMENT DEACTIVATES THE CURSOR
  114. 114. Select With Fetch DECLARE cursor statement defines a cursor with the specified name with an associated query as specified by the select that forms part of that declare. The declare cursor statement is not an executable code, but a purely declarative statement. A program can use any number of DECLARE CURSOR statements, and each of which must be of a different name. Open cursor statement generates executable code. The select clause used in the DECLARE CURSOR statement is effectively executed when the cursor is opened. This is done using the current value of the host variable (if used). This executable code will allow subsequent fetch statements to access the set of data that meets the definition of the DECLARE CURSOR‘s underlying SELECT statement. Opening the cursor is a must and DB2 will not open it on the first fetch. The FETCH statement will retrieves a row of data from the set made accessible by the open statement. Data is retrieved in host variables specified after the INTO clause of FETCH statement. After the first FETCH statement which retrieves the first row, the cursor will be advanced to the next row during the second FETCH operation and then assigns values from that row to host variables. After retrieving the required rows the CURSOR can be closed. The CLOSE CURSOR statement releases the cursor from the set of data.

×