db2

336
1 Application Programming Workshop Wu Chi Wu Chi 027- 87544884 027- 87544884 [email protected]

Upload: yboren

Post on 20-Jan-2015

5.384 views

Category:

Technology


14 download

DESCRIPTION

a db2 proarmmer's guide!

TRANSCRIPT

Page 1: Db2

1

Application Programming Workshop

Wu ChiWu Chi

027- 87544884027- [email protected]

Page 2: Db2

2

Application Programming Workshop

Prior to attending this course, the student should already have experience with one of the supported programming languages, COBOL or PL/I for z/OS, or C language for UNIX, Windows, and OS/2. Students are also expected to already be able to construct and use SQL statements.

Page 3: Db2

3

DB2 Slides -- IndexTopic Slide #

INTRODUCTION 4

TSO: Logging On and ISPF Initialization 21

DB2: Basics 37

DB2 Class Example 71

DB2 Concept 85

DB2 and Data Definition Language 110

DB2 and Data Control Language 142

DB2 and Data Manipulation Language (DML) 150

Batch TSO and Embedded SQL 175

DB2 and COBOL 228

EXPLAIN and Utilities in DB2 304

QMF: Query Management Facility 324

Page 4: Db2

4

DB2 Family

Page 5: Db2

5

DB2 Product Components

Page 6: Db2

6

Page 7: Db2

7

Introduction

Components of a DB2 environment:

•Users

•Data

•Programs(static,Dynamic)

•System

Page 8: Db2

8

End-User’s View

They See tables & issue SQL DML statementsDon’t see other programs;Don’t worry about data integrity, and so on

Page 9: Db2

9

Table:---> Table name Row having the same structure Column(Field) --> Column Name

The sequence of the rows is irrelevant

The sequence of the columns is irrelevant

Page 10: Db2

10

DML language

SELECT * FORM EMP WHERE EMPNO=‘000010’

UPDATE

INSERT

DELETE

Page 11: Db2

11

Static end usersUse specific programs(transactions) to perform specific actions on DB2 data.Need not knonw SQL, DB2

Page 12: Db2

12

The Static Program’s View

Contain built-in or embedded SQL statementsAt execution time, those SQL statements will be executed byLoading the needed access paths into storage and Completing the missing variables with input from a datasetor terminal.The access path is determined at compilation time, the accesslogic will always be the same.

Page 13: Db2

13

The Dynamic Program’s View

Don’t have complete built-in SQL statements but ask forthe SQL statements(or parts of SQL statements such asa WHERE clause) at Execution Time.

The access path could not be determined at compilation timesince a fundamental part of the statement, or the entire statement, was until execution of the program.

Page 14: Db2

14

Vendor Program View

Use a different interface to communicate with DB2:CLI(Call Level Interface) or ODBC.Similar to the use of dynamic SQL but reduce the need foradministration .DB2 environment setup need only once.Additional advantage: portability

Page 15: Db2

15

The Internet User’s View

Access DB2 without being aware of this fact.Net.data provides the user with the link between theWeb page and the database.

Page 16: Db2

16

Program’s View- General

Each program accesses tables as if it were the only one to do so.Doesn’t worry about: integrity, concurrency

Page 17: Db2

17

Program’s Responsibility:LUW(Logical Unit of Work)

A 2000 1000 1000 1000B 3000 3000 4000 4000

A 2000 1000 1000 2000B 3000 3000 4000 3000

Transfers $1000 from account A to account BLUW

UPDATE A

UPDATE A UPDATE B

UPDATE B

COMMIT

ROLLBACK

Page 18: Db2

18

Program’s Responsibility:Checkpoint / Restart

LUW

LUW

LUW

LUW

LUW

LUW

LUW

LUW

Page 19: Db2

19

The System’s View

DB2 receives many requests from many programs:Tso, Batch, CICS, IMS

DB2 also receives requests form UTILITIES: SPUFI, QMF(COPY, LOAD...) work at the OBJECT level Run in BATCH Compete with the user programs for resources Understand control statements, not SQL

CONCURRENTLY ACCESSING the same data

Page 20: Db2

20

The System’s ViewDB2’S Responsibilies SECURITY CONSISTENCY CONCURRENCY PERFORMANCE METADATA

Page 21: Db2

21

The DB2 Family

MAINFRAMEserversLANclients

Page 22: Db2

22

ROLES and Interfaces in DB2

Page 23: Db2

23

Application Life Cycle

Page 24: Db2

24

Logging on & ISPF Initialization

Page 25: Db2

25

To start a TSO session:

1. In win95, start a Winsock 3270 telnet session by clicking the start menu, general applications, communications, and then qws3270

You should have a window that looks like this:

Page 26: Db2

26

Continue to hit <ENTER> at *** until you get a READY prompt.If you have any problems or errors with ISPFINIT, please notify your instructor.

Once you successfully complete the ISPFINIT, at the READY prompt type: ISPF. Your screen should look like this:

Press <Enter> to remove IBM license message.

Note: All TSOsessions after this will begin

with thisISPF screen

after the initial logon.

Page 27: Db2

27

Before using DB2 you must allocate a partitioned dataset.

To Allocate a TSO partitioned dataset that will be used by DB2: Type ‘3’ at the Option prompt of the ISPF Primary

Option Menu then <ENTER>.

Page 28: Db2

28

Next: Type ‘2’ at the Option prompt of the Utility Selection Panel then <ENTER>

Page 29: Db2

29

Now: Type ‘A’ at the Option prompt of the Data Set Utility panel.

Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key.

Type your ‘USERID’

‘DB2’

‘SPUFI’

Page 30: Db2

30

Type ‘HZUWK3’

‘TRKS’

‘5’

‘5’

‘1’

‘FB’

‘80’

On the Allocate New Data Set menu: Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key.

Page 31: Db2

31

The other ISPF option you might find useful is ‘View’.

To use this option type a ‘1’ at the Option prompt of the ISPF Primary Option Menu.

Page 32: Db2

32

On the View Entry Panel: Use the ‘Tab’ key to move to next field to enter. When finished hit the <ENTER> key.

Type your ‘’

‘DB2’

‘SPUFI’

Page 33: Db2

33

On the View screen, you will see a listing of all the members in your ‘Z#.DB2.SPUFI’ account. Use the ‘Page Up’ and ‘Page Down’ buttons to scroll pages.

To see the contents of a dataset, use the ‘Tab’ key to position the cursor to the left of the name of the member, type an ‘S’, and hit <ENTER>

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999

Z999999.DB2.SPUFI

Page 34: Db2

34

The screen below is the result of the ‘S’ request on the ALTTAB member.

Z999999.DB2.SPUFI (ALTTAB)

Page 35: Db2

35

NOW to get to DB2:Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.

Page 36: Db2

36

Then from the next menu choose option ‘2’ -- DB2I.

Now you can start learning DB2!

Page 37: Db2

37

Type 2 to delete the data set without printing and then press <ENTER>.

Once you see the READY prompt you are out of ISPF.

• To logoff of the mainframe type: LOGOFF and press <ENTER>.

• To go back to ISPF type: ISPF and press <ENTER>

Logging off of TSO

To end a session of TSO, press F3 until you reach the “SpecifyDisposition of Log Data Set” panel.

Page 38: Db2

38

Type ‘2’ to delete without printing

Then press <ENTER> tochoose SYSOUT class A

and exit ISPF

Page 39: Db2

39

Then at the READY prompt, type either LOGOFF to terminate your

session or type ISPF to return to ISPF main menu

Page 40: Db2

40

Page 41: Db2

41

A relational DBMS that runs on IBM mainframe computers under MVS.

•Uses industry-standard SQL as central component.

•Allows for interactive, and application program processing

Interactive :

Customer Information Control System (CICS)

Information Management System (IMS)

Time Sharing Option (TSO) and DB2I

Application Programming : COBOL

DB2 (Database 2)

Page 42: Db2

42

DB2I TOPICS •SPUFI (SQL Processor Using File Input)

•DCLGEN•Program Preparation Panel•Running a program under DB2I

The following are good books on DB2:

• DB2 Developer’s Guide, Third Edition

by Craig S. Mullins

• DB2 for the COBOL Programmer, Part I: An Introductory Course

• DB2 for the COBOL Programmer, Part II: An Advanced Course

both by Steve Eckols

Page 43: Db2

43

Output(print)data set

» Allows you to interactively enter SQL statements, submit

them for execution, and get immediate feedback at your

terminal.

SPUFI (SQL Processor Using File Input)

Terminaluser

SPUFI DB2 Tables

Input data set

Page 44: Db2

44

To get to SPUFI in DB2:Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.

Page 45: Db2

45

Then from the next menu choose option ‘2’ -- DB2I.

Now type a ‘1’ at the “DB2I PRIMARY OPTION MENU

Page 46: Db2

46

SPUFI’s Main Menu consists of three sections:

1. Information about the input data set2. Information about the output data set3. Processing Options (steps SPUFI works through)

NOTE: The F1 help of SPUFI is NOT available.

Page 47: Db2

47

Input data set

Data set type: Sequential or partitionedAllocation: Must be already allocatedRecord size: 79 or 80 characters

• Input data sets contain the SQL statements you want to execute.

• If the data set is not cataloged or is password protected, you need to supply the appropriate information for the VOLUME SERIAL and DATA SET PASSWORD fields.

• The dataset name is the one you specified when allocating the dataset in TSO and should be:

‘DB2.SPUFI(member name)’Your USERID will be added to the front by

TSO• Record format either F or FB

Page 48: Db2

48

Output(print)

data set

Data set type: SequentialAllocation: May be allocated dynamicallyRecord size: 80 character minimum (4092 is the default)

• Output data set are the resulting tables from the processing of the SQL statements

• If the output data set does not exist, it will be created dynamically by DB2. However, if the data set already exists, DB2 will overwrite the existing data set with the resulting dataset of this session.

• Name your output dataset as followsRESULT

This dataset will be named ‘USERID.RESULT’ . This dataset will be overwritten after each execution. If you wish to keep a new result, name the dataset

‘RESULTn’.

Page 49: Db2

49

If you press <ENTER> after supplying the input and outputdata set information, SPUFI will then step through the enabled processing options in the order they appear in the SPUFI main menu.

There are 5 processing options: Change Defaults (leave this set to ‘NO’), Edit, Execute, Auto Commit, and Browse.

** After each option is completed, an asterisk replaces the **** YES next to that option in the main menu. **

Page 50: Db2

50

Change Defaults (leave this set to ‘NO’):

The change defaults panel allows you to change any of nineoptions that relate to the processing of input data sets and the format of the resulting output of that processing.

Page 51: Db2

51

1. ISOLATION LEVEL

2. MAX SELECT LINES

3. RECORD LENGTH

4. BLOCK SIZE

5. RECORD FORMAT

6. DEVICE TYPE

7. MAX NUMERIC FIELD

8. MAX CHAR FIELD

9. COLUMN HEADING

Used to create output data set.

The nine options are:

Page 52: Db2

52

ISOLATION LEVEL -- The performance and integrity, values RR (default,Repeatable Read) and CS(Cursor Stability).

MAX SELECT LINES -- specifies how many rows SPUFI will include in its output data set when it processes a SELECT statement (default is 250).

RECORD LENGTH, BLOCK SIZE, RECORD FORMAT, and DEVICE TYPE

Unless you use SPUFI output for something other than browsing in ISPF, you shouldn’t change these values.

Logical length must be at least 80.

The generic DEVICE type is SYSDA, which allows MVS to decide where to put the data set. Don’t change this setting unless you need to store the output on a specific volume.

Page 53: Db2

53

MAX NUMERIC FIELD -- maximum width a numeric column ofa table can have.

MAX CHAR FIELD-- maximum width of a character field.

COLUMN HEADING -- Lets you specify how SPUFI should identify the columns in its output.

NAMES names of columns as headings

LABELS names columns with values specified by DBA with SQL LABELS ON statement

ANY use any available label; uses names for any column without a label.

BOTH use both labels and column names for headings.

Page 54: Db2

54

EditEdit is where you can create or modify input files with the ISPF editor.

When you enter a “YES” at #6 of ‘Specify processing options’, you will enter “EDIT” mode.

Page 55: Db2

55

‘Z999999.DB2.SPUFI(SQLPGM)’

Create new Dataset: Use the Tab key to position yourself at the first column of the first empty line AND to move to the next line during typing.

Now start typing your SQL statements.

When you are finished, hitting return will cause the editor to place a ‘Bottom of Data’ message on the next line and quit insertion.

Page 56: Db2

56

Pressing F3 during an EDIT session will accept the new input file and return to the SPUFI main menu to executethe next step.

‘USERID.DB2.SPUFI(SQLPGM)’

PRESS ‘F3’

‘USERID.DB2.SPUFI(SQLPGM)’

Page 57: Db2

57

Modifying an existing Dataset: Use the Tab key to position yourself at the last column of the line numbers. Insert an ‘I’ and hit return.

A new line is created, insert mode is established. New lines can be entered using the <ENTER> key until an <ENTER> is pressed on a blank line at which time, insertion is stopped.

Page 58: Db2

58

A ‘d’ in the last column of the line numbers can be used to delete a line.

Also note: A comment is made by placing a ‘-’ in the first column of the code.

Note: The arrow keys and/or mouse may be used to position the cursor anywhere within the edit screen.

Page 59: Db2

59

EXECUTE

After editing the dataset, pressing F3 will return you to the SPUFI main menu with an ‘*’ in option #6 of ‘Specify processing options’ . Now press <ENTER> to go to next step which is the EXECUTION of the program named. (Option #7 must be set to “yes”.)

‘Z999999.DB2.SPUFI(SQLPGM)’

If option #9 is set to ‘YES’, you will immediately go into ’BROWSE OUTPUT’ upon completion of the execution.

Page 60: Db2

60

Auto Commit Commits any changes made by the executed SQL statements automatically.

(Leave ‘YES’ in option #8 of ‘Specify processing options’; we will always automatically commit.)

Browse Output Allows you to see the results of an execution. It displays the statements processed, resulting tables, and status information about the statements processed.

After all of the SQL is processed, SPUFI displays status lines for the entire session. Displays whether the changes were committed, and the statistics on the number of items processed during the session, both for input and output.

Page 61: Db2

61

A successful SQL operation is signified by a positive SQLCODE--usually a ‘0’ or a ‘100’.

Output of SQL Statements

For each SQL statement, SPUFI shows the number of rows affected and SQLCODE it returned.

Attribute Names

Data in RESULT dataset

Page 62: Db2

62

An error in DB2 is signified by a negative return code.

If an error occurs a screen such as the following one will occur. You should be able to fix the error by reading the message printed.

Page 63: Db2

63

Browsing output in SPUFI

Use the Page Up (F7)and Page Down (F8)keys to advance through the result of the SQL output by pages.

Use the Arrow keys to scroll through the result line-by-line.

Use the Arrow keys to scroll left and right through the result.

To issue a find command, at the command line type

‘FIND xxxxxxx’ (no quotes)

where ‘xxxxxxx’ is the value you wish to find. To issue another find of the same character string, hit F5. Repeated use of F5 causes subsequent finds of the same character string.

When finished Browsing, hitting the F3 key will take you back to the SPUFI main menu screen.

Page 64: Db2

64

Each SQL statement must end with a semi-colon. Correct: select * from Person;

Incorrect: select fac_SSN; from TEACHER;

Only one SQL statement per line.

Correct: Select * from Student where Student_SSN = 888888888; Select * from Course;

Incorrect: Select * from Student where GPA > 3.0; Select Fac_SSN from Teacher;

DB2I SQL RULES in SPUFI:

Page 65: Db2

65

SQL statements allowed under SPUFI

• Simple and complex SELECT statements and groups of statements• DML statements -- I.e. COMMIT, DELETE, INSERT, ROLLBACK, SELECT, and UPDATE

• DDL statements -- I.e. ALTER INDEX, ALTER TABLE, CREATE INDEX, CREATE SYSNONYM, CREATE TABLE, CREATE VIEW, DROP, and EXPLAIN

SQL statements not allowed under SPUFI

• Cursor-related processing• Dynamic SQL• Pre-compiler functions• Features related to program variables (Host and Indicator variables)

Page 66: Db2

66

EXAMPLES of DB2 SQL run in SPUFI

The following slides are examples of SQL statements that have been entered using SPUFI. The output is shown through the Browse option of SPUFI.

Example 1: Shows the complete process from the SPUFI main menu through the execution and back to the main menu.

Examples 2 - 3: Show only the SQL statements and the output browse screens.

Page 67: Db2

67

• Tab to the first space of the first line

• Enter documentation (use tab key to move between lines)

• Type the correct SQL statement (don’t forget the semicolon ‘;’ at the end.

• When finished hit <ENTER> and F3

Example 1 continued

Page 68: Db2

68

Example 1:Create a dataset called SHOWSTUD in your DB2 partitioned dataset using SPUFI that will list all the records in the STUDENT table.

Specify all the processing

options using the tab key.

When finished hit <ENTER>.

Page 69: Db2

69

Press <ENTER> to go to EXECUTE

Example 1 continued

Page 70: Db2

70

First Screen of

output

Hit Page Down to get to second

and last screen of output.

Example 1 continued

When finished hit F3 to go back to SPUFI main menu.

Page 71: Db2

71

Example 2:

Page 72: Db2

72

This is the output from two screens combined.

Example 2 continued

Page 73: Db2

73

Example 3:The SQL

dataset

The Output dataset with the “Count”

Displayed

Page 74: Db2

74

DB2 Class Example

Page 75: Db2

75

Relations

PERSON ( SSN, FNAME, LNAME, STREET_ADDRESS, CITY, STATE, ZIP, PHONE# )

STUDENT ( SSN, CLASSIFICATION, GPA, TOTAL_HOURS )

COURSE ( COURSE#, TITLE, DESCRIPTION, COURSE_LEVEL, CREDIT_HOURS )

TEACHER ( SSN, OFFICE#, OFFICE_PHONE# )

SECTION ( SECTION#, ROOM#, MEETING_DAYS, MEETING_TIME, MAX_ENROLL, FAC_SSN,

COURSE#, SEMESTER, YEAR )

TRANSCRIPT ( SSN, COURSE#, GRADE, SEMESTER, YEAR )

Page 76: Db2

76

Relationship Requirements

• One student may take many courses

• A student may take many sections, but only 1 section of a given course during a single semester

• One course can be taught by many instructors and taken by many students

• One teacher may teach many different courses during one semester

• A section of a course can be taught by only 1 instructor by can be taken by many students.

Page 77: Db2

77

Relationship Constraints• A person’s SSN, FNAME, and LNAME must present to be added to the database.• A student’s SSN must be present to be added to the database.• A student may take up to 20 credit hours from a maximum of 15 sections per semester.• A course’s COURSE# , TITLE and DESCRIPTION must be present to be added to the database.• A teacher’s FAC_SSN must be present to be added to the database.• One teacher may teach up to 5 sections from a maximum of 3 different courses during one semester.• A section’s SECTION#, MAX_ENROLL, COURSE#, SEMESTER, and YEAR must be present to be added to the database.• The number of students enrolled in a section must be <= MAX_ENROLL.• A transcript’s SSN, COURSE#, GRADE, SEMESTER, and YEAR must be present to be added to the database.

Page 78: Db2

78

PERSON

STUDENTTEACHER

Relations in Example Database

Page 79: Db2

79

COURSE

SECTION

Page 80: Db2

80

TRANSCRIPT

Page 81: Db2

81

Query 1

Query 2

Page 82: Db2

82

Query 3

Page 83: Db2

83

Query 4

Page 84: Db2

84

Query 5

Page 85: Db2

85

Query 6

Page 86: Db2

86

Query 7

Page 87: Db2

87

Query 8

Page 88: Db2

88

And SQLAnd SQL

Page 89: Db2

89

DB2 ConceptDB2 Data Structures

• Database• Storage Group• Table Spaces• Tables• Indexes• Views

Page 90: Db2

90

DB2 Structure Storage Group: STG1

(STOGROUP)

DATABASE DB1

INDEX A

INDEX C

TABLE A

TABLE B

Tablespace: TS1

TABLE C

Tablespace: TS2

Storage Group: STG2

Page 91: Db2

91

DB2 Structure Definitions

STORAGE GROUP: STOGROUP -- A DB2 definition for a set of physical DASDs that the tablespaces are allocated onto.

TABLESPACE: The physical structure (VSAM files) that contains the actual table or tables and index data.

DATABASE: The logical defintion which relates a set of tablespaces to each other, and also relates particular storage groups to tablespaces and indexes.

TABLE: The object which actually contains all the data. It consists of rows and columns.

Page 92: Db2

92

DB2 Concept The Hierarchy of DB2 Structures

Database D1

Table T1

Table T2

Table space S1

Index X1

Index X2

Table T3Part 1Table T3Part 2

PartitionedTable space S2

Partitioned index X3 Part 2Partitioned index X3 Part 2

Storage GroupG1

3390

StorageGroup G2

3380

Page 93: Db2

93

DB2 Concept The Hierarchy of DB2 Structures

StorageGroup

Database

TableSpace

Table

Column

Index

View

Alias

Synonym

Page 94: Db2

94

DB2 ConceptDatabase/Storage Groups

Database• contain all the data associated with one application or with group of related application• allows you to start or stop access to all the data in one operation and authorization for access to all the data as a single unit

Storage Groups

• a set of DASD volumes from which DB2 can assign space for tablespaces and indexspaces • all volumes of a given storage group must the same device type

Page 95: Db2

95

DB2 ConceptTable Spaces

Table Spaces

• is one or more data sets in which one or more tables are stored• can consist of from 1 to 64 VSAM data sets which can together contain up to 64 gigabytes• are divided into equal-sized units, called pages(4k), which are written to or read from DASD in one operation• types of Table Space

Simple Table Spaces Segmented Table Spaces Partitioned Table Spaces

Page 96: Db2

96

DB2 Concept Simple Table Spaces

Simple Table Spaces

page

page

page

page

page

page

• Not partitioned or segmented• can contain more than one table• the rows of different tables are not keep separate • find all the rows of one table can require scanning the entire table space• if a table is dropped, its rows are not deleted. • Space occupied by the rows does not become available until the table space is reorganized

Table Space

Page 97: Db2

97

page

Segment 3

page

Segment 2

Segment 1

page

Table A

Table B

Table C

DB2 Concept Segmented Table Spaces

Segmented Table Spaces

• divided into groups of pages called segments, each the same size• intended to hold more than one table• each segment contains rows from only one table • not necessary to scan the entire table space but only the segments that contain that table to search all the rows for one table • if a table is dropped, its segments become immediately reusable.

Table Space

Page 98: Db2

98

DB2 Concept Partitioned Table Spaces

Partitioned Table Spaces

• divided into separate units of storage called partitions, each containing a part of one table• can be independently assigned to separate storage groups• improved data availability • improved utility performance • improved efficiency in table space and index scan

page

Partition 3

page

Partition 2

Partition 1

page

Key rangeA~H

Key rangeI~Q

Key rangeR~Z

Table Space

Page 99: Db2

99

DB2 ConceptTable/Index

Table

• collections of rows all having the same columns• all the data in a given column must be of the same data type• can have a primary key whose values uniquely each row

Index

• an ordered set of pointers to the data in a DB2 table• stored separately from the table• can create an index on a table any time after you create the table• users of the table are unaware that an index is being used. DB2 decides whether or not to use the index to access the table• Improve performance• ensure uniqueness

Page 100: Db2

100

DB2 Concept Views

Views

• an alternate way of representing data that exists in one or more tables• can include all or some of the columns from one or more base tables• can be based on other views or on a combination of views and tables• can be used as though it were a table• a table has a storage representation but a view does not. DB2 just stores the definition of the view in the DB2 catalog • cannot create an index on it

User 1

Table 1 Table 2 Table 3 Table 4

View 1 View 2 View 3

User 2

Page 101: Db2

101

Physical Design IssueDesigning Tables and View

• decide what data to record in database• define tables for each type of relationship

• one to many and many to one• many to many• one to one

• normalize your tables to avoid redundancy• consider denormalizing your tables for performance• consider creating views of your tables

• to provide a customized table for a specific user• to limit access to certain kinds of data • to allow you to alter tables without affecting application program

DB2 ConceptPhysical Design Issue

Page 102: Db2

102

DB2 ConceptPhysical Design Issue

Physical Design IssueDesigning Columns• Choose a name for the column

• column name• name must unique within in table• max length is 18 bytes• First character alphabetic

• column labels• give a more descriptive column heading for a column name

• What kind of data is valid for the column• string data type• numeric data type• date, time and timestamp

Page 103: Db2

103

Physical Design IssueDesigning Columns

DATA TYPE

String Data Type

CHAR(x)CHARACTER(x)

VARCHAR(X)

* Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as "page" size.

DESCRIPTIONfixedlength string

variablelength string(or longerthan 254 char)

LENGTHx characters(maximum 254)

0 to xcharacters(maximum 4K*)

DB2 ConceptPhysical Design Issue

Page 104: Db2

104

Physical Design IssueDesigning Columns

Double byte Data Type

DATA TYPEGRAPHIC(x)

VARGRAPHIC(x)

* Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as "page" size.

DESCRIPTIONfixed length string

variablelength string(or longerthan 127 char)

LENGTHx characters(maximum 128)

0 to xcharacters(maximum 2K*)

DB2 ConceptPhysical Design Issue

Page 105: Db2

105

Physical Design IssueDesigning Columns

Numeric Data Type

DATA TYPESMALLINT

INTEGERINT

DECIMAL(x,y)DEC(x,y)NUMERIC(x,y)

FLOAT(m)REAL

FLOATFLOAT(n)DOUBLE PRECISION* Approximately **1 <= m <= 21, 22 <= n <= 53

DESCRIPTIONWhole numbers

Whole numbers

x digits, of which y are to the right of the decimal point

short floatingpoint **

log floatingpoint **

RANGE 32K*

2 Billion

up to 32digits

5.4E-79 to7.2E+75

5.4E-79 to7.2E+75

DB2 ConceptPhysical Design Issue

Page 106: Db2

106

Physical Design IssueDesigning Columns

Date, Time, Timestamp Data Type

DATA TYPEDATE

TIMETIMESTAMP

INTERNAL FORMATyyyymmdd

hhmmssyyyymmddhhmmssnnnnnn(nnnnnn = microseconds)

DB2 ConceptPhysical Design Issue

Page 107: Db2

107

Physical Design IssueDesigning Columns

• Which columns might need default values• Null value

• not a zero, a blank, an empty string• any column can contain null values

• Default value• specified with the DEFAULT clauses in CREATE TABLE or ALTER TABLE• can be either DB2-defined or user-defined • DB2-defined defaults

• Number : zero String : blank • Date : current date Time : current time• Timestamp : current timestamp

DB2 ConceptPhysical Design Issue

Page 108: Db2

108

Physical Design IssueDesigning Index• a table can have more than one index • index key can use one or more columns(2-64 columns)• column updates require index updates• a composite key might be useful than a key on a single column when the comparison is for equality• indexes are important tools for improving performance• DB2 allow you to enter duplicate values in a key column• in a composite key the index entries can be in sequence by the ascending values or descending values

DB2 ConceptPhysical Design Issue

Page 109: Db2

109

Physical Design Issue

• Primary Key : The column or set of columns that provide the unique identifiers of the row• Foreign Key : A column or set of columns that refer to a primary key • Parent and Dependent Table: The table containing the primary key is called the parent table and the one containing the foreign key is the dependent table

Data Integrity - Terminology

DB2 ConceptPhysical Design Issue

Page 110: Db2

110

DEPTNO...

C01

DEPTNAME.......

INFORMATION CENTER

PRIMARYKEY

OPERATIONS...

...

...

...

...

...E11

DEPARTMENT table

FOREIGNKEY

EMPNO

000030

000090

000130

000290

000300....

FIRSTNM

SALLY

EILEEN

DOLORES

JOHN

PHILIP....

LASTNAM

KWAN

HENDERSON

QUINTANA

PARKER

SMITH....

...

...

...

...

...

...

...

DEPT

C01

E11

C01

E11

E11...

...

...

...

...

...

...

...

PRIMARYKEY

EMPLOYEE table

DB2 ConceptPhysical Design Issue

Page 111: Db2

111

DB2 Concept --Referential Integrity

• By definition, a FOREIGN KEY in one table matches a PRIMARY KEY in another table

• A PRIMARY KEY value must be UNIQUE, and cannot be NULL

• A FOREIGN KEY value must match a PRIMARY KEY or be NULL

• DB2 enforcement of referential constraints:• INSERT/UPDATE/LOAD of FOREIGN KEY

- Must match PRIMARY KEY or be NULL• UPDATE of PRIMARY KEY

- Not allowed if any FOREIGN KEYS match original value• DELETE of PRIMARY KEY

- Rules specified by owner of table CASCADE SET NULL RESTRICT

Referential Integrity

Page 112: Db2

112

When removing a primary key (DELETE)what should be done to matching foreign keys?

1. DELETE rows with matching values (CASCADE)

2. Change matching values to null (SET NULL)

3. Disallow the DELETE if matching values exist (RESTRICT)

Referential Integrity

DB2 Concept --Referential Integrity

Page 113: Db2

113

Page 114: Db2

114

SQL Summary

SQL

Data Definition Language

(DDL)

Data Manipulation

Language (DML)

Data Control Language

(DCL)

CREATE

DROP

ALTER

SELECT

INSERT

UPDATE

DELETE

GRANT

REVOKE

Page 115: Db2

115

DB2 Programming Concept

SQL 语言特性:

.取代传统的 DO PROCEDURE LANGUAGE .程序设计者只需申明需要哪些资料,不需申明如何取得这些资料 .不仅是数据查询工具,也能进行数据管理 .命令语法易学易懂 - SELECT * FROM DA. TBDAMF WHERE APPLID = 'DA'; - UPDATE DA.TBDAMF SET FILE = 'AAAAAA' WHERE EMPNO = '111111';

Page 116: Db2

116

Page 117: Db2

117

Data Definition Language (DDL)

CREATE statement:

CREATE STOGROUP

CREATE DATABASE

CREATE TABLESPACE

CREATE TABLE

CREATE INDEX

CREATE VIEW

CREATE SYNONYM

DROP statement:

DROP STOGROUP

DROP DATABASE

DROP TABLESPACE

DROP TABLE

DROP INDEX

DROP VIEW

DROP SYNONYM

ALTER statement: ALTER STOGROUP

ALTER TABLESPACE, ALTER TABLE, ALTER INDEX

Page 118: Db2

118

Data Definition Language (DDL) -- CREATE

CREATE STOGROUP stogroup-name VOLUMES volume-id

VCAT catalog-name PASSWORD password;

CREATE STOGROUP IBMST001 VOLUMES ACA301 VCAT DSNCATPASSWORD OSESME;

Creates a storage group at the current server. Storage from the identified volumes can later be allocated for table spaces and index spaces.

CREATE STOGROUP

Privilege Needed:

CREATESG or SYSADM or SYSCTRL

Page 119: Db2

119

Data Definition Language (DDL) -- CREATE

CREATE DATABASE database-name STOGROUP stogroup-name

CCSID [ ASCII | EBCDIC ];

CREATE DATABASE IBMDB001 STOGROUP IBMSG001 CCSID EBCDIC;

Defines a DB2 database at the current server.

CCSID: Specifies the default encoding scheme for data stored in the database. The default applies to the table spaces created in the database. All tables stored within a table space must use the same encoding scheme.

CREATE DATABASE

Privilege Needed:

CREATDBA or CREATDBC or SYSADM or SYSCTRL

Page 120: Db2

120

Data Definition Language (DDL) -- CREATE

CREATE TABLESPACE tablespace-name IN database-name USING STOGROUP stogroup-name;

CREATE TABLESPACE IBMTS001 IN IBMDB001 USING STOGROUP IBMSG001;

Defines a simple, segmented or partitioned table space at the current server.

CREATE TABLESPACE

Other parameters: SEGSIZE, BUFFERPOOL, LOCKSIZE, LOCKMAX, COMPRESS, CCSID, LOCPART, MAXROWS

Privilege Needed:

CREATETS or DBADM or DBCTRL or DBMAINT or SYSADM or SYSCTRL

Page 121: Db2

121

Data Definition Language (DDL) -- CREATE

CREATE TABLE table-name ( column-definition,

unique-constraint, referential-constraint )

LIKE table-name

IN database-name.tablespace-name;

Defines a table at the current server. The definition must include its name and the names and attributes of its columns. The other parameters are optional.

CREATE TABLE

Privilege Needed:

CREATETAB or DBADM or DBCTRL or DBMAINT or SYSADM or SYSCTRL

Note: There are more optional parameters that are used for fine tuning a table and that will not be covered here. See the DB2 manual for an explanation of these.

Page 122: Db2

122

Data Definition Language (DDL) -- CREATE TABLE

Column-definition: column-name

data-type NOT NULL

[ UNIQUE | PRIMARY KEY ]

WITH DEFAULT [ constant |

NULL ]

references-clause

Column-name: Names a column of the table. Do not use the same name for more than one column of the table. A table can have use to 750 columns.

Page 123: Db2

123

Data Definition Language (DDL) -- CREATE TABLE

Data-type: Specifies one of the following types:

SMALLINT 2 bytes PIC S9(4) COMP

INTEGER 4 bytes PIC S9(9) COMP

REAL 4 bytes PIC USAGE COMP -1

FLOAT(1..21) 4 bytes PIC USAGE COMP -1

DOUBLE PRECISION 8 bytes PIC USAGE COMP -2

FLOAT(22..53) 8 bytes PIC USAGE COMP -2

DECIMAL (m,n) (m/2)+1 bytes PIC S9(m-n)V9(n) COMP -3

continued on next slide

Page 124: Db2

124

Data-type: continued

CHARACTER(n) n bytes PIC X(n)

VARCHAR(n) 2 to n+2 01 VARCHAR. bytes 49 LENGTH PIC S9(4) COMP.

49 COLUMN PIC X(n).

GRAPHIC(n) 2n bytes PIC G(n) DISPLAY -1

VARGRAPHIC(n) 2 to 2n+2 01 VGRAPHIC. bytes 49 LENGTH PIC S9(4).

49 COLUMN PIC G(n) DISPLAY -1.

DATE 4 bytes PIC X(10) YYYYMMDD

TIME 3 bytes PIC X(8)

TIMESTAMP 10 bytes PIC X(10)

Data Definition Language (DDL) -- CREATE TABLE

Page 125: Db2

125

Data Definition Language (DDL) -- CREATE TABLE

NOT NULL -- prevents a column from containing null values.

CREATE TABLE TAB001(PROJECT-NO CHAR(6) NOT NULL, …. );

PRIMARY KEY -- provides a shorthand method of defining a primary key composed of a single column. If coded in the definition of a column it is equivalent to coding the PRIMARY KEY as a separate clause.

UNIQUE -- provides a shorthand method of defining a unique key composed of a single column. If coded in the definition of a column it is equivalent to coding the UNIQUE as a separate clause.

CREATE TABLE TAB002(PROJECT-NO CHAR(6) NOT NULL

PRIMARY KEY, ….);

Page 126: Db2

126

WITH DEFAULT [constant | NULL] -- assigns a value to the column in the absence of a value specified on INSERT or LOAD. If a value is not specified after DEFAULT, the default value depends on the data type of the column.

CREATE TABLE TAB001( …. PROJECT-NAME CHAR(20) WITH DEFAULT NULL,

…. );

Data Definition Language (DDL) -- CREATE TABLE

Page 127: Db2

127

References clause -- REFERENCES table-name (column-name) ON DELETE [ SET NULL |

RESTRICT | CASCADE ]

-- provides a shorthand method of defining a foreign key composed of a single column. If coded in the definition of a column, the effect is the same as it that references-clause were specified as part of a FOREIGN KEY clause.

-- ON DELETE -- the delete rule of the relationship as follows: SET NULL -- set the foreign key attributes to NULLRESTRICT -- if there are tuples in the referenced table, cause an

error to occurCASCADE -- if there are tuples in the referenced table, delete the

tuples with the matching foreign key value

CREATE TABLE TAB001(…. ACCT-DEPT CHAR(3)

REFERENCES TAB002 (ACCT-DEPT) ON DELETE SET NULL, ….);

Data Definition Language (DDL) -- CREATE TABLE

Page 128: Db2

128

Data Definition Language (DDL) -- CREATE TABLE

unique-constraint -- PRIMARY KEY(column-name,...) -- defines a primary key composed of the identified columns. The columns named MUST be defined as NOT NULL.

-- UNIQUE(column-name,…) -- defines a unique key composed of the identified columns. Each column named MUST be defined as NOT NULL. A UNIQUE key definition is a duplicate it it is the same as the PRIMARY KEY.

*** NOTENOTE: With either unique-constraint definition, in most circumstances the table is marked as unavailable until its primary key index is explicitly created. ***

CREATE TABLE TAB001(PROJECT-NO CHAR(6) NOT NULL, ….

….,PRIMARY KEY (PROJECT-NO) )IN IBMDB001.IBMTS001;

Page 129: Db2

129

Data Definition Language (DDL) -- CREATE TABLE

referential-constraint -- FOREIGN KEY constraint-name (column-name,...) REFERENCES table-name (column-name,….)

ON DELETE ….

-- defines a referential constraint with the specified name. A name is generated if constraint-name is not specified.

CREATE TABLE TAB001(PROJECT-NO CHAR(6) NOT NULL, ACCT-DEPT CHAR(3), ACCT-LOC CHAR(2), ….

….,PRIMARY KEY (PROJECT-NO)FOREIGN KEY IBMFK001 (ACCT-DEPT, ACCT-LOC)

REFERENCES TAB002 (DEPT, LOC) ON DELETE SET NULL ) ….

Page 130: Db2

130

Data Definition Language (DDL) -- CREATE TABLE

LIKE table-name or view-name -- specifies that the columns of the table have exactly the same name and description as the columns of the identified table or view. The name specified after the LIKE must identify a table or view that exists at the current server and MUST have at least a SELECT privilege set (权限) .

CREATE TABLE TAB003 LIKE TAB001;

IN database-name.tablespace-name or

IN DATABASE database-name

-- names the database and tablespace in which the table is created. Both forms are optional. Default is IN DATABASE DSNDB04.

CREATE TABLE TAB001 …….

IN IBMDB001.IBMTS001;DVLPDB.DVLPTS

Page 131: Db2

131

Data Definition Language (DDL) -- CREATE

CREATE INDEX

Creates a partitioned or nonpartitioned index and an index space at the current server. The columns included in the key of the index are columns of a table at the current server.

Privilege Needed: INDEX or DBADM or SYSADM or SYSCTRL

CREATE [ TYPE n ] [ UNIQUE ] INDEX index-name ON table-name (column-name [ ASC | DESC ] , …. )USING STOGROUP storage-group-nameCLUSTER;

Note: There are more optional parameters that are used for fine tuning a table and that will not be covered here. See the DB2 manual for an explanation of these.

Page 132: Db2

132

Data Definition Language (DDL) -- CREATE INDEX

TYPE n -- specifies the type of index, 1 or 2

UNIQUE -- prevents the table from containing two or more rows with the same value of the index key. A table requires a unique index if a table has a UNIQUE or PRIMARY KEY clause in the CREATE TABLE statement. If the table already contains rows with duplicate key values, the index is not created.INDEX index-name -- names the index. The name, including the implicit or explicit qualifier, must not identify an index that is described in the catalog. The qualifier must not be SYSIBM, SYSCAT,SYSFUN, or SYSSTAT.

ON table-name -- identifies the table on which the index is created. The name must identify a table in the current server. The table must be a base table (not a view)

Page 133: Db2

133

column-name [ ASC | DESC ] -- specifies the columns of the index key. Each column-name must identify a column of the table. 16 columns or less may be specified.ASC is ascending( 升 ) order and is the default. DESC means put the index entries in descending order.

USING STOGROUP -- identifies a storage group that exists at the current server and the privilege set must include SYSADM, SYSCTRL, or USE stogroup for this storage group.

CLUSTER -- specifies that the index is the cluster index of the table. The cluster factor of a clustering index is maintained or improved dynamically as data is inserted into the associated table, by attempting to insert new rows physically close to the rows for which the key values of this index are in the same range. Only one clustering index may exist for a table so Do not use CLUSTER if CLUSTER was used in the definition of an existing index on the table.

Page 134: Db2

134

Data Definition Language (DDL) -- CREATE INDEX

If the named table already contains data, CREATE INDEX creates the index entries for it. If the table does not yet contain data, CREATE INDEX creates a description of the index; the index entries are created when data is inserted into the table.Creating an index with a schema name that does not already exist will result in the implicit creation of that schema provided the authorization ID of the statement has IMPLICIT_SCHEMA authority. The schema owner is SYSIBM. The CREATEIN privilege on the schema is granted to PUBLIC.

CREATE UNIQUE INDEX IBMDB001.IBMNX001ON IBMDB001.TAB001 ( PROJECT-NO ASC)USING STOGROUP IBMSG001

CLUSTER;

Page 135: Db2

135

Data Definition Language (DDL) -- CREATE

CREATE VIEW

Creates a view on tables or views at the current server. Privileges are needed for each table or view referenced in the subselect.

CREATE VIEW view-name ( column-name , …. ) AS subselectWITH [ CASCADED | LOCAL ] CHECK OPTION;

Privilege Needed: SELECT (on each table or view) orOwnership of the table orDBADM or SYSADM or SYSCTRL

Page 136: Db2

136

Data Definition Language (DDL) -- CREATE VIEW

view-name -- names the view. The name, including the implicit or explicit qualifier, must not identify a table, view, nickname or alias described in the catalog.The qualifier must not be SYSIBM, SYSCAT, SYSFUN, or SYSSTAT

column-name -- names the columns in the view. If you specify a list of column names, it must consist of as many names as there are columns in the result table of the subselect.

AS subselect -- defines the view. At any time the view consists of the rows that would result if the subselect were executed.

CREATE VIEW IBMDB001.IBMVW001(PROJNO, PROJNAME, PROJDEP, EMP-NAME)AS SELECT PROJNO, PROJNAME, PROJDEP,EMP-NAME

FROM PROJECT, EMPLOYEEWHERE EMP-NO = ‘12349’;

Page:2-35

Page 137: Db2

137

The Disappearing Row

1.Create View EMPV AS Select * from EMP Where Salary > 0;

2.Insert Into EMPV Values(‘000260’,...,-6000,...);

3.Select * From EMPV Where EMPNO = ‘000260”;

The inserted row disappeared!

Data Definition Language (DDL) -- CREATE VIEW

Page 138: Db2

138

WITH …. CHECK OPTION -- specifies the constraint that every row that is inserted or updated through the view must conform to the definition of the view. DB2 enforces this constraint whenever rows of the view are inserted or updated. If the search condition is not true for an inserted or updated row, an error occurs and no rows are inserted or deleted.

CASCADED -- Update and insert operations on view V must satisfy search conditions of view V and all underlying views, regardless of whether the underlying view were defined with a check option.

LOCAL -- This form lets you update or insert rows that do not conform to the search condition of view V. This operation can be performed if the view is defined on a view that was defined without a check operation.

Data Definition Language (DDL) -- CREATE VIEW

Page 139: Db2

139

Default Value is cascade when using V5, prior to V5 will use the local syntax.

The check option can only be specified on a view that is not read-only and that does not include a subquery else the SQLCODE will be -160.

1.Create View EMPV AS Select * from EMP Where Salary > 0

With Check Option;

2.Insert Into EMPV Values(‘000260’,...,-6000,...);

Data Definition Language (DDL) -- CREATE VIEW

error occurs and no rows are inserted

Page 140: Db2

140

Read-Only View:

-Involves a join

-Contains a column function

-Includes a GROUP BY clause

-Contains the DISTINCT keyword

-Contains a column derived from an expression or a scalar function

Insertable View:

--A view is insertable if ALL columns of the view are updatable and the fullselect of the view does not include UNION ALL.

A view definition cannot contain UNION or ORDER BY clause

(DDL) -- CREATE VIEW ( View Restrictions)

Page 141: Db2

141

(DDL) -- CREATE VIEW ( View Catalog Information)

SYSIBM.SYSTABLESSYSIBM.SYSCOLUMNSSYSIBM.SYSVIEWSSYSIBM.SYSVIEWDP

Since views are virtual tables, Db2 will keep information aboutthem as if they were tables.In addition, the view’s definition will be stored as well as dependency information.All tables in the db2 catalog have the owner SYSIBM

Page 142: Db2

142

(DDL) -- CREATE VIEW ( Good Reasons to use views)

Good reasons to use views• Views for simplicity

-Elimination of unwanted data-Elimination of redundant coding

•Views for security on data content•Views for (Program)data independence(partial)•Views to customize column names•Views to validate data for specific users(CHECK OPTION)

Page 143: Db2

143

Data Definition Language (DDL) -- DROP

DROP -- deletes an object at the current server. Except for storage groups, any objects that are dependent on that object are also deleted. Whenever an object is deleted, its description is deleted from the catalog at the current server.

Privileges Needed:

To drop a table, tablespace or index: Ownership or DBADM

To drop an alias, storage group, or view: Ownership or SYSADM or SYSCTRL

To drop a database: DROP privilege or DBADM orDBCTRL or SYSADM or SYSCTRL

To drop a synonym: Ownership

Page 144: Db2

144

Data Definition Language (DDL) -- DROP

DROP DATABASE database-name;

DROP INDEX index-name;

DROP STOGROUP storage-group-name;

DROP TABLE table-name;

DROP TABLESPACE tablespace-name;

DROP VIEW view-name;

DROP SYNONYM synonym;

Page 145: Db2

145

Page 146: Db2

146

Data Control Language (DCL)

GRANT Statement: Grants authorization of functions and levels.

GRANT privilege TO [ authorization-name | PUBLIC ]

WITH GRANT OPTION;

System-Wide Functions:

SYSADM: A user has TOTAL CONTROL over any DB2 resource and may grant and/or revoke from any other user the authority to access any resource (expect for the actual creator of any object).

GRANT SYSADM TO T90XXX1;

SYSOPR: A user has the ability to issue certain DB2 commands and has no access to DB2 tables.

Page 147: Db2

147

Data Control Language (DCL)-- GRANT

Other system-wide authorities:

BINDADD: Allows user to create new application plans using the BIND subcommand with the ADD option.

CREATEDBA: Allows user to create new databases and automatically gives DBADM authority over those databases.

GRANT CREATEDBA TO T90XXX1, T90YYY1, … ;

CREATEDBC: Allows user to create new databases and automatically gives DBCTRL authority over those database.

CREATESG: Allows user to create new storage groups.

STOSPACE: Allows user to use the STOSPACE utility.

TRACE: Allows user to start and stop DB2 traces using the -START TRACE and -STOP TRACE

Page 148: Db2

148

Database Wide Functions:

DBADM: A user has total control over those databases granted at this level of authority. This includes altering and creation of tables, creation of tablespaces, seeing and modifying data in all tables, and running appropriate utilities. The user can grant lower levels of authority to the objects in his defined database IF the user has been given GRANT option.

DBCTRL: Allows a user to run utilities and to create tables and tablespaces. The user cannot access data in the tables that have been created by another user in the same tablespace without being granted specific access by the creator of the table or a SYSADM priviledge.

GRANT DBADM ON DATABASE IBMDB001TO PUBLIC ;

Data Control Language (DCL)-- GRANT

Page 149: Db2

149

Other database-level authorities:

CREATETAB: Allows user to create tables in any existing tablespace in this database.

CREATETS: Allows user to create tablespaces in this database.

DISPLAYDB: Allows user to check the database and tablespace in this database through execution of the -DISPLAY DATABASE command.

DROP: Allows user to drop the database.

IMAGECOPY: Allows user to run the COPY and MERGECOPY utilities against tablespaces in this database.

LOAD: Allows user to run the LOAD utility to load tables in the database.

GRANT CREATETS ON DATABASE IBMDB001TO T90XXX, T90YYY, T90ZZZ, …. ;

Data Control Language (DCL)-- GRANT

Page 150: Db2

150

Other database-level authorities:

RECOVERDB: Allows user to run the RECOVER and MODIFY utilities against tablespaces in this database.

REORG: Allows user to run the REORG utility against tablespaces and indexes in this database.

REPAIR: Allows user to run the REPAIR utility against tablespaces and indexes in this database.

STARTDB: Allows the user to start this database by issuing the -START DATABASE command.

STATS: Allows user to run the RUNSTATS and CHECK utility against tablespaces and indexes in this database.

STOPDB: Allows the user to stop this database by issuing the -STOP DATABASE command.

Data Control Language (DCL)-- GRANT

Page 151: Db2

151

Table-level Authorities:

SELECT: Allows view-only access to data within a table or that data defined by a view.

UPDATE: Allows user update capability to data within a table or data defined by a view.

DELETE: Allows user delete capability for rows within a table.

INSERT: Allows user to insert new rows in a table.

ALTER: Allows user to be able to alter a table or view by adding a column.

UPDATE USING COLUMN-NAME(s): Allows user to update ONLY those columns that have been specified in the GRANT statement.

ALL: Allows the user to have all the above privileges.

GRANT SELECT ON TAB001 TO PUBLIC;

GRANT ALL ON TAB001 TO T90XXX, T90YYY;

Data Control Language (DCL)-- GRANT

Page 152: Db2

152

Data Control Language (DCL)

REVOKE Statement: Revokes privileges from authorization.

REVOKE privilege ON DATABASE

FROM [ authorization-name | PUBLIC ]

[ BY authorization-name | ALL ];

privilege: Names one or more privileges.

authorization-name: Lists one or more authorization Ids.

REVOKE DBADM ON DATABASE FROM PUBLIC;

REVOKE CREATETS ON DATABASE FROM T90XXX1;

REVOKE USE OF STOGROUP IBMSG001 FROM PUBLIC;

REVOKE USE OF TABLESPACE IBMTS001 FROM T90XXX1;

Page 153: Db2

153

And And DMLDML

Page 154: Db2

154

Data Manipulation Language (DML)

INSERT statementInserts rows into a table or view. Inserting a row into a view also inserts the row into the table on which the view is based.

Two forms:

INSERT via VALUES is used to insert a single row into the table or view using the values provided or referenced.

INSERT via SELECT is used to insert one or more rows into the table or view using values from other tables and/or views.Privilege Needed:

On a table: INSERT on table or Ownership or DBADM or SYSADM;

On a view: INSERT on view or SYSADM

Page 155: Db2

155

Data Manipulation Language (DML) -- INSERT

INSERT INTO [ table-name | view-name ] VALUES (.., .., .., .., ..);

INSERT INTO [ table-name | view-name ] (column-name, …, …, )VALUES (.., .., .., .., ..);

INSERT INTO [ table-name | view-name ]subselect;

INSERT INTO [ table-name | view-name ] (column-name, …, …, )subselect;

Page 156: Db2

156

Data Manipulation Language (DML) -- INSERT

INSERT INTO TAB001VALUES (‘00024’, ‘Mary’, ‘D11’, 15);

INSERT INTO TAB002(CUSTOMER-ID, CUSTOMER-NAME, CUSTOMER-ROOM-NUMBER, CUSTOMER-AGE) VALUES (‘00024’, ‘Mary’, ‘D11’, 15);

INSERT INTO VIEW001SELECT * FROM TAB003;

INSERT INTO VIEW002SELECT * FROM TAB003 WHERE GPA > 3.0;

Page 157: Db2

157

Data Manipulation Language (DML) -- INSERT

INSERT Rules:

Default values: If a value is not included in the value list, the default value is used. Columns that do not have a default value MUST have a value in the value list.

Uniqueness Constraint: If the identified table or base table of a view has one or more unique indexes, each row inserted into the table must conform to the constraints imposed by those indexes.

Referential Constraint: Each non-null value of a foreign key must be equal to some value of the parent key of the parent table in the relationship.

Omitting the column list: If column list is omitted, a value for every column that is present in the table must be presented.

Page 158: Db2

158

Data Manipulation Language (DML)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.

Two forms:

The searched UPDATE form is used to update one or more rows, optionally determined by a search condition.

The positioned UPDATE form is used to update exactly one row, as determined by the current position of a cursor.

Privilege Needed:

User-defined table: UPDATE privilege or Ownership or DBADM or SYSADM

View: UPDATE on view or SYSADM

Page 159: Db2

159

Data Manipulation Language (DML) -- UPDATE

Searched update:

UPDATE [ table-name | view-name ]SET column-name = [ expression | NULL ] , column-name = [ expression | NULL ], .., .., WHERE search-condition;

Positioned update:

UPDATE [ table-name | view-name ]SET column-name = [ expression | NULL ] , column-name = [ expression | NULL ], .., .., WHERE CURRENT OF cursor-name;

Page 160: Db2

160

Data Manipulation Language (DML) -- UPDATE

UPDATE TAB001SET PHONE-NUMBER = ‘815-753-6945’WHERE EMPLOYEE_NUMBER = ‘E293’;

UPDATE TAB001SET SALARY = SALARY + 100WHERE EMPLOYEE_NUMBER = ‘E948’;

Embedded in COBOL:

EXEC SQLUPDATE TAB003

SET SALARY = 2 * SALARYWHERE CURRENT OF CURSOR1;

END-EXEC.

Page 161: Db2

161

Data Manipulation Language (DML) -- UPDATE

UPDATE rules:

If the update value is then the column MUST

NULL allow NULL values

number be a numeric column

character string be a character string with appropriate length

graphic string be a graphic string with appropriate length

datetime value be a DATE, TIME or TIMESTAMP column

Page 162: Db2

162

Data Manipulation Language (DML) -- UPDATE

UPDATE rules continued:

Uniqueness constraint: The updated row must conform to any constraints imposed on the table by any unique index on an updated column.

Referential constraint: A non-null update value of a foreign key must be equal to some value of the parent key of the parent table of the relationship.

Page 163: Db2

163

Data Manipulation Language (DML)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.

Two forms:

The searched DELETE form is used to delete one or more rows, optionally determined by a search condition.

The positioned DELETE form is used to delete exactly one row, as determined by the current position of a cursor.Privilege Needed: User-defined table: DELETE privilege or Ownership or

DBADM or SYSADM

On a view: DELETE privilege or SYSADM

Page 164: Db2

164

Data Manipulation Language (DML) -- DELETE

Searched delete:

DELETE FROM [ table-name | view-name ]WHERE search-condition;

Positioned delete:

DELETE FROM [ table-name | view-name ]WHERE CURRENT OF cursor-name;

Page 165: Db2

165

Data Manipulation Language (DML) -- DELETE

DELETE FROM TAB001WHERE DEPT-NUMBER = ‘E11’ OR DEPT-NUMBER = ‘D21’;

Embedded in COBOL program:

EXEC SQLDELETE FROM TAB003

WHERE CURRENT OF CURSOR1; END-EXEC.

Page 166: Db2

166

Access Paths Typical access paths:Table(space) scanMatching index scanNo-matching index scanIndex-only access

The Access Path is determined by the Optimizer in DB2.It can be influenced by the way you write your SQL statement.

SQL Statement Performance-access path

Page 167: Db2

167

Access Paths

DB2 --SQL Statement Performance

Examples: Phonebook has an index on LASTNAME, FIRSTNME

Table(space) Scan:

SELECT * FROM PHONEBOOK SELECT * FROM PHONEBOOK WHERE ADDRESS LIKE ‘%AVE%’

Matching Index Scan:

SELECT LASTNAME, FIRSTNME, PHONENO FROM PHONEBOOK WHERE LASTNAME LIKE ‘S%’

Page 168: Db2

168

Access Paths

DB2 --SQL Statement Performance

Index-Only Matching Index Scan :

SELECT FIRSTNME FROM PHONEBOOK WHERE FIRSTNME LIKE ‘S%’

No-Matching Index Scan:

SELECT LASTNAME, FIRSTNME, PHONENO FROM PHONEBOOK WHERE FIRSTNME = ‘ABE’

Page 169: Db2

169

Access Paths Howell,Thurston(1) Peters,Joan(2)Zidler,Bob(3)

Adams,Mark(2,1)(5,2) Alviani,Cart(7,2) Bennett,Barb(2,3)Champman,Mike(5,1)Davis,Mac(3,1)Howell,Thurston(3,2)

Jefferson,Tom(4,1)Jones,Bob(1,1)Lee,Spike(4,2)Lincoln,Abe(7,1)Mitchell,David(2,3)Peters,Joan(1,3)

Quinn,tony(6,2)Reeves,Susan(1,2)Smith,Stanley(8,2)Smith,Steve(8,1)Thompson,Tom(6,3)Zidler,Bob(6,1)

Jones,BobReeves,SusanPeters,Joan

Adams,MarkMitchell,DavidBennett,Barb

Davis,MacHowell,Thurston.

Jefferson,TomLee,Spike.

Champman,MikeAdams,Mark.

Zidler,BobQuinn,TonnyThompson,Tom

Lincoln,AbeAlvani,Cart.

Smith,SteveSmith,Stanley.

Data Pages

Root Page

Leaf Pages

Page 170: Db2

170

SQL Statement Performance

1. Avoid Numeric Conversions

SELECT A INTO :B

- Column A and host-variable B should be

same data type and scale

...WHERE A = :B

2. SELECT Only the columns you will use

Additional columns = additional CPU

3. Avoid SELECT *

- External changes to the table can cause

errors or warnings

DB2 --SQL Statement Performance

Page 171: Db2

171

4. If Possible, Use Join Logic instead of Correlated Subselect

SELECT EMPNO, LASTNAME

FROM TEMPL, TPROJ

WHERE WORKDEPT = DEPTNO

AND EMPNO = RESPEMP

is more efficient than

SELECT EMPNO, LASTNAME

FROM TEMPL

WHERE WORKDEPT =

(SELECT DEPTNO FROM TPROJ

WHERE RESPEMP = X.EMPNO)

DB2 --SQL Statement Performance

Page 172: Db2

172

5. MINIMIZE DB2 SORT PROCESSING

Don't request sequencing unless necessary

- Additional CPU

- Additional I/O to temporary database

Consider Using an External Sort instead of ORDER BY

- For a large number of rows

- Will require more Virtual Storage in user Address Space

- Reduces contention 争夺 for DB2 temporary database

Allow DB2 to consider INDEX to avoid sort

DB2 --SQL Statement Performance

Page 173: Db2

173

6. Using an INDEX can:

. Save a tablespace scan

. Avoid a sort

7. Whether an existing index is usable for this access to the

data

- Dependent on statement coding

DB2 --SQL Statement Performance

Page 174: Db2

174

INDEXEDColumn is...

DB2's USE OF INDEXES

Used with: IN LIKE BETWEEN >,>=,<,<=,>,<,= =,<> NOT OR ORDER BY GROUP BY DISTINCT^

Compared to:longer literalarithmetic exp.diff. data type

Used for JOIN

INDEXCandidate

YESNOTE1

YESYESNO

NOTE2NOTE3

YESYESYES

NONONO

YES

SortCandidate

YESYESYES

YES

NOTE1 : YES, except when string is host-variable, or string is of the form '%...' or '-...'NOTE2 : Apply NOT, then evaluateNOTE3 : NO unless convertible to in

DB2 --SQL Statement Performance

Page 175: Db2

175

SELECT...WHERE C1 = :HV+100 . CANNOT use index

------------

HV = HV+100...SELECT...WHERE C1 = :HV . CAN use INDEX

SELECT...FROM TEMPL,TDEPT WHERE WORKDEPT = DEPTNO AND WORKDEPT = 'E11' . Can use index on WORKDEPT for initial selection

------------SELECT...FROM TEMPL,TDEPT WHERE WORKDEPT = DEPTNO AND WORKDEPT = 'E11' AND DEPTNO = 'E11' . Allows DB2 to use index on WORKDEPT or

DEPTNO for initial selection

DB2 --SQL Statement Performance

Page 176: Db2

176

DB2 --SQL Statement Performance

SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12' OR WORKDEPT = 'B12' . Can use index (DB2 can convert to IN)

WHERE WORKDEPT IN('A12' , 'B12‘)

SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12' OR WORKDEPT > 'B12' . CANNOT use index

------------SELECT ... FROM TEMPL WHERE WORKDEPT = 'A12’ UNION ALL SELECT ... FROM TEMPL WHERE WORKDEPT > 'B12' . CAN use index

Page 177: Db2

177

USE BETWEEN IF POSSIBLE

SELECT ... FROM TEMPL WHERE WORKDEPT >= 'A00' AND WORKDEPT <= 'C99' . Can use index, but...

---------------- SELECT ... FROM TEMPL WHERE WORKDEPT BETWEEN 'A00' AND 'C99' Makes more efficient use of the index

DB2 --SQL Statement Performance

TO EXPLAIN

Page 178: Db2

178

Page 179: Db2

179

DB2 Programming Concept SAMPLE PROGRAM REVIEW

SAMPLE PROGRAM REVIEW

BATCH PROGRAM

ON-LINE PROGRAM

Page 180: Db2

180

Batch TSOSQL statements can be executed in DB2:

• in the background

• under control of TSO terminal monitor program

JCL to run a program in batch:

//jobname,……//JOBLIB DD DSN= db2 load library name//BATCHTSO EXEC PGM=IKJEFT01,DYNAMNBR=20//SYSTSPRT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//SYSUDUMP DD SYSOUT=*//SYSTSIN DD *

DSN SYSTEM(db2 program name) RUN (name of program to run) - PLAN(name of the plan to use) - LIB(‘application library’)/*//

Page 181: Db2

181

//T90xxxnn JOB ,'Your Name',MSGCLASS=A,REGION=0K/*JOBPARM ROOM=##,TIME=3,LINES=5,Q=F//JOBLIB DD DSN=SYS2.HLA.V120.LOADLIB,DISP=SHR// DD DSN=SYS3.DB2.V510.SDSNLOAD,DISP=SHR//DROPTABS EXEC PGM=IKJEFT01,DYNAMNBR=20//SYSTSPRT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//SYSUDUMP DD SYSOUT=*//SYSTSIN DD * DSN SYSTEM(DSN1) RUN PROGRAM(DSNTIAD) PLAN(DSNTIA51) PARM('RC0')- LIBRARY('SYS3.DB2.V510.RUNLIB.LOAD') END/*//SYSIN DD * DROP TABLE PERSON; DROP TABLE STUDENT; DROP TABLE COURSE; DROP TABLE SECTION; DROP TABLE TEACHER; DROP TABLE TRANSCRIPT; DROP DATABASE IBMDB001;/*//

Batch TSO

JCL to execute SQL statements IN STREAM

Page 182: Db2

182

DB2 Embedded SQL -- Program Preparation

Source Program

Precompiler

DCLGEN

DBRM

Modified Source

Compiler

Compiled Source

Linkage Editor

Load Module

Bind Package

PackageBind Plan

Plan

DB2 Catalog

DB2 Directory

Page 183: Db2

183

DB2 PROGRAM PREPARATION

Complilers Do Not Understand SQL

Who will get rid of the EXEC SQL so that your program can be compiled?•.The PRECOMPILER(PC) will replace the delimiter flags with CALLS•Ii will also verify whether

-Your SQL statements are correct

-Your host variables match the db2 datatypes

NOT access DB2

EXEC SQL DECLARE TABLE

EXEC SQL

DECLARE EDUCS99.EMP99 TABLE

(EMPNO CHAR(6) NOT NULL,

LASTNAME . . .)

END EXEC.

DB2 Embedded SQL -- Program Preparation

声明 TABLE 结构

Page 184: Db2

184

Declaration Generator

DCLGEN creates source code output that it stores as a member of a Partitioned Data Set (PDS).

You can use this output in place of coding table declarations and host variables.

DCLGEN can save you time coding and, because DCLGEN extracts the information to create host variables definitions directly from the DB2 catalog, you can be sure those definitions are accurate.

Embedded SQL -- DCLGEN

DVLP.BOOKLIB(EMPXXRCD)

Page 185: Db2

185

In DCLGEN Panel you provide three types of information:

1. Identify table you want to create host variables for

2. Name the output data set that will hold the declarations

DCLGEN will produce.

3. Specify processing options for the DCLGEN run.

Embedded SQL -- DCLGEN

To Use DCLGEN, select option 2 from the DB2I Primary Option Menu.

EMP99EDUCS99

‘DVLP.BOOKLIB(EMP99RCD)’

EMP99DCL

Page 186: Db2

186

Option 1 : SOURCE TABLE NAMEThe name of the base table that you would like to make a table declaration and host variables for.

Option 2 : TABLE OWNER (optional)The name of the owner of the table (if table is not your own)

Option 3 : AT LOCATION (optional)This is the location of the source table specified in option 1. If no location is given, the default location is used. This is normally omitted.

Embedded SQL -- DCLGEN

EMP99DVLP

Page 187: Db2

187

Option 4: DATA SET NAMEHere you specify the name of the output data set that will hold the declarations. It can be a sequential data set or a member of a pre-existing PDS.

Sequential data sets should have 80-character records and must exist before you run DCLGEN.

You can create a new partitioned data set member with DCLGEN as long as the library that will hold the member already exists.

Option 5 : DATA SET PASSWORDIf the data set has a password, specify it here.

Embedded SQL -- DCLGEN

‘DVLP.BOOLIB(EMP99RCD)’

Page 188: Db2

188

Option 6 : ACTIONSpecifies what DCLGEN will do if library member already in use.

ADD -- DCLGEN only allows you to add a new member to the destination data set.

REPLACE -- DCLGEN will delete old library member, if exists, and create new one. (normally used)

Embedded SQL -- DCLGEN

Page 189: Db2

189

Option 7 : COLUMN LABEL By specifying ‘YES’, DCLGEN is caused to include values DBA coded with LABELS ON statement. These labels are added as comments to the DCLGEN output.

Embedded SQL -- DCLGEN

Option 8 : STRUCTURE NAMEUses the specified name as the group name for the host variables items. If you leave this option blank, DCLGEN will append the name of the table to ‘DCL’.

DCLGEN uses the name of the columns in the table as the names for the host variables.

EMP99DCL

Page 190: Db2

190

Option 9 : FIELD NAME PREFIXSpecifies an up to 28 character long string that will be concatenated with a different number for each column to be used for the column name. The original names of the columns are included in the output, but only as comments. This is normally left blank.

Embedded SQL -- DCLGEN

EMP99DCL

Page 191: Db2

191

The PRECOMPILE-Functions• Includes DCLGEN members• Includes SQLCA• Looks for SQL statements and for the definition of host variables• Verifies SQL syntax• Matches each column and table name in the SQL to the

DECLARE TABLE statements• Prepares the SQL for compilation or assembly in the host

language• Produces a DBRM and stores it in a PDS user's library• Can be invoked in DB2I or batch

DOES NOT ACCESS DB2

DB2 Embedded SQL -- Program Preparation

Page 192: Db2

192

SQL INCLUDE Statement

INCLUDE member-name•used to include DCLGEN output•Nested INCLUDE not allowed•Any source can be included

Cobol program code:

EXEC SQL INCLUDE EMP99RCDEND EXEC.

PAGE:3-24

Page 193: Db2

193

SQL Communication Area - SQLCA

SQL Stmt

SQLCA

Program checksreturned values

Execute SQL stmt

and

Updatesthe

CommArea

Program DB2

SQLCODE

Page 194: Db2

194

SQL INCLUDE SQLCA Statement

Used to Include SQLCA declaration

Cobol program code:

EXEC SQL INCLUDE SQLCAEND EXEC.

The precompiler generate an SQLCA in your program

Page 195: Db2

195

Embedded SQL -- 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 PIC X(8).

Page 196: Db2

196

DB2 Embedded SQL -- Program Preparation

The DB2 precompiler produces a DBRM (DataBase Request Module) and a modified source program with the SQL statements commented out.

The DB2 BIND command turns a DBRM into an executable format.

The DB2 Catalog stores information about the plan and package.

DB2 Directory stores the actual plan and package.

Page 197: Db2

197

Program Preparation-Precompile

DBRM:

DataBase Request Module is a module containing SQL statements extracted from a source program by the DB2 precompiler. It is stored as a member of a partitioned data set. It is NOT stored in the DB2 catalog or DB2 directory.

A DBRM

•Contains extracted , parsed SQL source

•Is stored as a member in a partitioned dataset

•One member created per precompile

•Will become input to BIND

DVLP.DBRM

Page 198: Db2

198

When a DBRM is bound into a plan, all its SQL statements are placed into the SYSIBM.SYSSTMT DB2 Catalog table. When a DBRM is bound into a package, all its SQL statements are placed into the SYSIBM.SYSPACKSTMT table.

One DBRM corresponds to exactly one source module.

Program Preparation-Precompile

Page 199: Db2

199

Program Preparation-Precompile

Modify Source Precompiler replaced the SQL statements with a CALL to

module DSNHLI(High Level Language Interface) .

In COBOL, SQL-TIMESTAMP-1 and SQL-TIMESTAMP-2

represent the upper and lower portions of the modified store-

clock value. The value of SQL-STMT-NUM corresponds with the

statement numbers of the precomplier listing.

Although often call a timestamp, SQL-TIMESTAMP-1 and SQL-

TIMESTAMP-2 make up the consistency token, which is a

modified store-clock value(not to be confused with the

timestamp data type). COBOL’s two-part timestamp is due to its

lack of support, at the time, for a 32-bit binary data field.

Page 200: Db2

200

Modify SourceCALL DSNHLI parameters:

•DBRM name(SQL-PROG-NAME)•Timestamp(SQL-TIMESTAMP-1,SQL-TIMESTAMP-2)•Statement Number(SQL-STMT-NUM)

Other parameters:•Addresses of host variables•Addresses of SQLCA

At this stage,the two components, DBRM and modified source, will part and won’t see each other again until program execution.Therefore, the call must include all necessary information for db2 to be able to locate the access path needed to execute the SQL statement associated with the call.

Program Preparation-Precompile

Page 201: Db2

201

Compilation and LINK-EDIT

•After precompilation ,you have to compile and link-edit--This can be done using: .DB2I panels .JCL•CICS COMMAND TRANSLATOR may have to be invoked

The link-edit will have to include the necessary modules for the call to work properly.OS/390 Supports many execution enviroments:TSO,CICS,IMS, and so forth.In the link-edit step different interface modules will have to be included. They have the same entry point:DSNHLI.

Page 202: Db2

202

BIND PACKAGE

BIND PACKAGE runs in TSO(Online or Batch)BIND PACKAGE creates a package in the DB2 directory

FUNCTIONS:•Validates SQL•Resolves table names•checks privileges•chooses an access path based on catalog statistics•stores source SQL in catalog•stores executable access path(PACKAGE) in DB2 directory

Page:3-38

Page 203: Db2

203

DB2 Embedded SQL -- Program PreparationPackage:

A package is a single, bound DBRM with optimized access paths. By using packages, the table access logic is “packaged” at a lower level of granularity, at the package or program level. To execute a package, it must be included in the package list of a plan. Packages are NEVER directly executed--they are ONLY indirectly executed when the plan in which they are contained executes.

When a package is bound, DB2 access the following tables:SYSIBM.SYSCOLDIST SYSIBM.SYSCOLDISTATATS SYSIBM.SYSCOLSTATS SYSIBM.SYSCOLUMNS SYSIBM.SYSINDEXES SYSIBM.INDEXSTATS SYSIBM.PACKAGE SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKAUTH SYSIBM.SYSTABLES SYSIBM.SYSTABLESPACE SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH

Information about packages is stored in the following tables:

SYSIBM.SYSPACKAGE SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKDEP

SYSIBM.SYSPACKSTMT SYSIBM.SYSPKSYSTEM SYSIBM.SYSTABAUTH

Page 204: Db2

204

PACKAGE

DBRM

BIND PACKE(collx)MEMBER(dbrma)

collx

dbrma

dbrmb

Dbrm...

BIND PACKE(colly)MEMBER(dbrma)

colly

dbrma

dbrmb

Dbrm...

Package name=collection_id.package_id

Page 205: Db2

205

Collection(packageset)A collection is a set of packages.A package is bound in a collecion.A collection is implicitly created at first BIND PACKAGEreferring to that collection.Example:BIND PACKAGE(online) MEMBER(pkg1)BIND PACKAGE(batch) MEMBER(pkg3)

online

pkg1

pkg2

batch

pkg3

pkg4

Page 206: Db2

206

Collection(packageset)

A package can be bound in multi collecions in a single DB2 system.

Example:BIND PACKAGE(test_payroll) MEMBER(pkg1)BIND PACKAGE(prod_payroll) MEMBER(pkg1)

test_payroll

pkg1

pkg2

prod_payroll

pkg1

pkg3

Page 207: Db2

207

Locating PACKAGEs at execution time

Mprog1call DSNHLI (dbrm1,,1)...call DSNHLI (dbrm1, ,2)...

Mprog1...call DSNHLI (dbrm2, ,1)...

Call

Call call

DB2 Directory

collx

dbrm1 dbrm3

colly

dbrm1

collz

dbrm2 dbrm4?

Page:3-44

Page 208: Db2

208

Locating PACKAGEs at execution time

Mprog1call DSNHLI (dbrm1,,1)...call DSNHLI (dbrm1, ,2)...

Mprog2...call DSNHLI (dbrm2, ,1)...

Call

Call call

DB2 Directory

collx

dbrm1 dbrm3

colly

dbrm1

collz

dbrm2 dbrm4

Page:3-44

Collx.dbrm1,collz.*

plana

BIND PLAN(plana)Pklist(Collx.dbrm1,collz.*)

Page 209: Db2

209

Locating PACKAGEs at execution time

How does DB2 find the right package with the right timestamp?Several packages exist in different collections with the same timestamp(different BIND PACKEGE with same input DBRM), which package will DB2 use?There is a missing link.

Page 210: Db2

210

PLAN and PACKAGEs

PLAN:An additional structure that will guide DB2 in its search for the appropriate package.A package can only be located and executed via a PLANA PLAN contains a PACKAGE LIST, a list of logical pointers to packages which makes specific parts of the directory eligible for the packake search.The dbrm name and the timestamp provided with the call is used to locate the correct package via the package list.DB2 will look for the right(same timestamp) package by going through each entry in the package list in turn until it has a hit.Running a DB2 program is done by associating the plan with the load module. This is done outside the program.

RUN PROGRAM(mprog1) PLAN(plana)

Page 211: Db2

211

Plans are created by the BIND PLAN command.

BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*)

When a plan is bound, DB2 reads the following DB2 catalog tables:SYSIBM.SYSCOLDIST SYSIBM.SYSCOLDISTSTATS SYSIBM.SYSCOLSTATS SYSIBM.SYSCOLUMNS SYSIBM.SYSINDEXES SYSIBM.SYSINDEXSTATS SYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSTABLESSYSIBM.SYSTABLESPACE SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH

Information about plans is then stored in the following tables:SYSIBM.SYSDBRM SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKLISTSYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSPLANDEPSYSIBM.SYSPLSYSTEM SYSIBM.SYSSTMT SYSIBM.SYSTABAUTH

PLAN and PACKAGEs

Page 212: Db2

212

BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*)

BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*)MEMBER(dbrma,dbrm1)

BIND PLAN(plana) MEMBER(dbrma,dbrm1)

BIND PLAN - DBRMS

collx.dbrm1,collz.*

plana

collx.dbrm1,collz.*

planb

dbrma

dbrm1

planc

dbrm1

dbrm2

Instream DBRM

Page 213: Db2

213

PACKAGE Search

collx.dbrm1,collz.*

plana

collx.dbrm1,collz.*

planb

dbrma

dbrm1

planc

dbrm1

dbrm2

...CALL DSNHLI(dbrm1, ,1)...

Instream DBRM first!

Page 214: Db2

214

collx.dbrm1,colly.*

plana

collx.dbrm1,colly.*planb

dbrma

dbrm1

planc

dbrm1

dbrm2

...CALL DSNHLI(dbrm1, ,1)...

Timestamp Mismatch Errors

Sqlcode: -818

Sqlcode: -805

colly

dbrm1

Page 215: Db2

215

Running the Program

TSO

RUN PROGRAM(mprog1) PLAN(plana)

CICS RCT(Resource Control Table)

IMS RTT(Resource Translate Table)

CAF Callable Interface(DSNALI)

RRSAF DSNRLI

Page 216: Db2

216

LINK-EDIT

Each execution environment hasits own language interface

TSO using DSN DSNELI

TSO or BATCH using CAF DSNALI

IMS DFSLI000

IMS with multiple DB2S DFSLIxxx

CICS DSNCLI

RRSAF DSNRLI

Page 217: Db2

217

BIND - QUALIFIER Option

...SELECT ... FROM TAB1

...

dbrm

BIND PACKAGEQUAL(TEST)

BIND PACKAGEQUAL(PROD)

BIND PACKAGE

TEST.TAB1 binder.TAB1 PROD.TAB1

binder

BIND PACKAGE OR PLAN

Page 218: Db2

218

TABLE Mirroring-1

...SELECT ... FROM TAB1

...

dbrm

BIND PACKAGE(usdcol)QUAL(usd)

USD.TAB1 YEN.TAB1

dbrm1

usdcol

BIND PACKAGE(yencol)QUAL(yen)

dbrm1

yencol

Same structure

Page 219: Db2

219

TABLE Mirroring-2

... SELECT ... FROM TAB1

...

USD.TAB1 YEN.TAB1

dbrm1

usdcol

BIND PLAN(plan1)Pklist(usdcol.*,yencol.*)

dbrm1

yencol

lmod1usdcol.*,yencol.*

plan1

Page 220: Db2

220

TABLE Mirroring-3

coll = ‘yencol’.SET CURRENT PACKAGESET=:coll.SELECT ... FROM TAB1

USD.TAB1 YEN.TAB1

dbrm1

usdcol

BIND PLAN(plan1)Pklist(usdcol.*,yencol.*)

dbrm1

yencollmod1

usdcol.*,yencol.*plan1

Page 221: Db2

221

Special Register-CURRENT PACKAGESET

CURRENT PACKAGESET

Blank First look at all DBRMs in PLAN then look at collections

not blank Only look in the specified collection, disregard DBRMs or any other collection

EXEC SQL SET CURRENT PACKAGESET = ‘COL1’

SET CURRENT PACKAGESET will activate only the entries in the package list that refer to that particular collection

Page 222: Db2

222

PACKAGE VERSIONING

pgma

UTTEST.SRC

Precompileversion(uttest)

Precompileversion(systest)

pgma

UTTEST.LOAD

pgma

SYSTEST.LOAD

BIND PACKAGE(collx) MEMBER(pgma)

pgma

collx

pgma

pgma

UTTEST.SRC

Page 223: Db2

223

Data Consistency- Isolation LevelRR (Repeatable Read)

The contens of a data row or page will not change until the program commits.With the RR, all row(page) locks are held as the data is accessed. Locks are held on all rows that are touched, even no-qualifying rows(not meet all WHRERE conditions). They are not released until the next commit point. This locks out all other application processes from accessing these rows or pages, guaranteeing the consistency of the data, until the commit point.A row ‘touched’ by the program will remain unchanged until the user COMMITS or ROLLBACKS.If the same SELECT is repeated within the same LUW, you would get the same exact answer set.Although RR ensures the data consistency, it is very restrictive for those applications that need concurrent access to the data.

Page 224: Db2

224

Data Consistency-Isolation Level

CS(Cursor Stability)

When a data row is read by a program, its contents are

available for update by other programs as soon as the data

access is finished. That is, a row ‘read’ is released as soon

as the data is read.This option allows for maximum concurrency, but additional logic will be needed in the program(REFRESH).

Page 225: Db2

225

Data Consistency-Isolation Level

RS(Read Stability)

DB2 takes a lock on the row or page it accesses but only holds those locks where the rows satisfy the WHERE conditions, permmitting more concurrency than RR. Locks on the qualifying rows are held until the program issues a commit.No other application process can update or delete a row that is part of the answer set. Thus your update can be performed without consistency problems.However, it is possible that more row s can be inserted into table or no-qualifying rows can be updated to satisfy the original WHERE conditions. If the same SELECT is repeated within the same LUW, you might not get the same answer set.

Page 226: Db2

226

Data Consistency-Isolation Level

UR(Uncommitted Read)READ without integrity check. UR is applicable in those cases where the statement is read-only and where there is no risk for an integrity exposure.Isolation UR has some powerful capabilities as it is able to read through locks. However, it should be used with great care since it can cause serious consistency problems.

All of these isolation levels can be set at the statement, package, or plan level.

Page 227: Db2

227

Data Consistency-Isolation Level

Conclusions:

1. Modified data is always hidden until the modifier commits unless you specify UR.

2. If you specify isolation(RR or RS), read data will additionally BE PROTECTED AGAINST UPDATES until the reader commits.

Commit as soon as possible after updates.Don’t use RR but re-read the data instead before or during the update operation.If you want to protect qualifying data that has been read, you should use RS instead of RR.

Page 228: Db2

228

DB2 Embedded SQL -- Program Preparation

Package benefits:

1. Reduced bind time. If packages are NOT used when multiple DBRMs are bound into a plan and the SQL within one of those programs changes, the entire plan must be rebound.

2. Smaller granularity of bind parameters. Bind options can be specified at the program level.

3. Versioning. Packages can be versioned, thus enabling multiple versions of the same package existing at the same time in the DB2 catalog. Simply by running the appropriate load module, DB2 chooses the correct package to execute. DB2 uses a package selection algorithm to execute the correct access path.

Page 229: Db2

229

FREE / DROP

TSO

SQL

FREE PLAN(plan-id,...) FREE PACKAGE(collection-id. package-id(version-id))

DROP PACKAGE collection-id.package-id VERSION version-id

Deleting a package or plan from the DB2 system

Page 230: Db2

230

SourceProgram

DCLGEN

Precompiler

DBRM BindPackage

Package

Plan

DB2Catalog

DB2Directory

ModifiedSource(SQL)

Compiler

CompiledSource

LinkageEditor

LoadModule

CICSTRANSLATE

ModifiedSource

EXEC SQL 转换成 CALL 语句

EXEC CICS 转换成 CALL 语句Plan

Package

Package

Package

Package

Package

Package

•一个 Package 一个程序•每个 Package 包括 Access Path

translateispfediter

dclgen

Program Preparation-Summary

Version level

Page 231: Db2

231

DB2 AND COBOL

Page 232: Db2

232

DB2 Programming Concept DB2 Application Structure

DB2 Application Structure

․ WORKING STORAGE SECTION - INCLUDE TABLE STRUCTURE - INCLUDE SQLCA - CURSOR DECLARATION

․ PROCEDURE DIVISION - ERROR HANDLING - DML SQL STATEMENT - CURSOR HANDLING - CHECK SQLCODE

Page 233: Db2

233

Embedded SQL

Two types or embedded SQL statements:

1. Singleton SELECTs -- MUST select only ONE row. And MUST contain INTO clause. Here the names of thehost variables that will accept the data returned by DB2 are listed.

2. Cursor SELECTs -- Processes multiple rows.

Page 234: Db2

234

• Each statement must begin with EXEC SQL and end with END-EXEC:

EXEC SQLINCLUDE CUSTRCD

END-EXEC.•All SQL statements must be coded in columns 12 - 72.

• To continue text from one line to another, code as much of the string as you can on the first line, then on subsequent lines, the first non-blank character needs to be a quotation mark.

• When you have reached the end of the string, code a closing quotation mark. (Whether or not to use single or double quotation marks depends on the options you use for the DB2 pre-compiler.)

Embedded SQL- SQL Coding Rules

Page 235: Db2

235

• Don’t code an SQL statement in a COBOL Copy member.

• When one SQL statement immediately follows another, always code a period after the first’s END-EXEC

Embedded SQL- SQL Coding Rules

EXEC SQLINCLUDE CUST

END-EXEC.

EXEC SQLINCLUDE SQLCA

END-EXEC.

Page 236: Db2

236

What you DON’T code for a DB2 Table:

1. A COBOL SELECT statement2. A File Description entry3. A Record Description

What you DO or CAN code:

1. INCLUDE statement for SQL Communications Area2. Table Declarations3. Host Variables4. Cursors

Embedded SQL

Page 237: Db2

237

SQL Communications Area:

SQLCA is a set of fields through which DB2 passes back information about the success of an executed SQL statement.

• SQLCA must be defined in each DB2 COBOL program.• To have the precompiler include the SQLCA fields in your program code the following in your WORKING-STORAGE section:

EXEC SQLINCLUDE SQLCA

END-EXEC.

Embedded SQL -- SQLCA

Page 238: Db2

238

Embedded SQL -- 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 PIC X(8).

Page 239: Db2

239

•The most important field in the SQLCA is the SQLCODE which is DB2’s return code field.

SQLCODE values:

Zero (0) -- Execution successfulPositive -- Statement successful, but with some

exceptional condition+100 -- Row not found or end of dataNegative -- Serious error detected (Statement failed)

You want to check the SQLCODE after every EXEC SQL you code to be sure that the SQL statement was successful.

Embedded SQL -- SQLCA

Page 240: Db2

240

•SQLSTATE is a cross-platform SQL return code contained in a 5 digit character string.

SQLSTATE values:‘00000’ success‘01ddd’ warning‘02000’ not found‘else’ error

Recommended that: you use SQLSTATE instead of SQLCODE

Embedded SQL -- SQLCA

Page 241: Db2

241

Table Declarations are not required but do offer good documentation. Also, when table declarations are present,the DB2 pre-compiler uses it to verify errors that might otherwise get through. Table declarations should be coded in WORKING-STORAGE

The following code declares the table PERSON: EXEC SQL DECLARE PERSON TABLE ( SSN CHAR(9) NOT NULL,

FNAME CHAR(10) NOT NULL,LNAME CHAR(10) NOT NULL,ADDRESS CHAR(20),CITY CHAR(12),STATE CHAR(2),ZIP CHAR(5),PHONE CHAR(10) )

END-EXEC.

Embedded SQL -- Table Declarations

Page 242: Db2

242

Host Variables are fields that DB2 uses to move data to and from your program and a table.

You can define host variables in DATA DIVISION’s WORKING-STORAGE OR LINKAGE SECTION.

You would code host variables as a level 10 variable.

For example,

FNAME CHAR(10) NOT NULL

is the table declaration of FNAME.

A host variable to FNAME would be:

10 FNAME PIC X(10)

Embedded SQL -- Host Variables

Page 243: Db2

243

Level - 01 items are called host structures. A host structure is a named set of elementary items.

With DB2 you can only create host structures with two levels, for relational tables are two-dimensional, with no structures nested inside other structures.

DB2 doesn’t support repeating groups. So there will be NO OCCURS clause in any host variable definitions.

There are 7 basic data types for data in DB2 tables:

1. CHAR 5. DATE2. SMALLINT 6. TIME3. INTEGER 7. TIMESTAMP4. DECIMAL

Embedded SQL -- Host Structures

Page 244: Db2

244

Basic Data types Typical COBOL Definition

CHAR 10 CITY PIC X(20).character (EBCDIC) data

SMALLINT 10 SMALL-CNT PIC S9(4) COMP.Halfword integer data

INTEGER 10 LARGE-CNT PIC S9(9) COMP.Fullword integer data

DECIMAL 10 INVOICE-TOTAL PIC S9(7)V99 COMP-3.Packed-decimal data

DATE 10 INVOICE-DATE PIC X(10).Date Data (yyyy-mm-dd)

TIME 10 INVOICE-TIME PIC X(8).Time data (hh.mm.ss)

TIMESTAMP 10 INVOICE-TIMESTAMP PIC X(26).Date and time data, with microseconds (yyyy-mm-dd-hh.mm.ss.mmmmmm)

Embedded SQL -- Data Types

Page 245: Db2

245

When using host variables in SQL statements, you must precede the host variable name with a colon(:).

Example:EXEC SQL

SELECT FNAME, LNAME, ADDRESSINTO :FNAME, :LNAME, :ADDRFROM PERSONWHERE PERSON.SSN = :SSN

END-EXEC.

When executed FNAME, LNAME, and ADDRESS items will be put into the host variables FNAME, LNAME, and ADDR (respectfully) from the tuple in PERSON table, whose SSN matches the one in the host variable SSN.

Embedded SQL -- Host Variable

Page 246: Db2

246

In order to be able to process a results table that contains more than one row, you have to use cursors.A cursor is a pointer that identifies the current row in a results table. A cursor can only point to one row at a time. - Is required for SELECT of multiple rows - Is never used for INSERT - May be reused (CLOSED + new OPEN) - Will be close at COMMIT unless declared with WITH HOLD

Muliple cursors: - May be defined in a program - May work with the same table - May be open simultaneously

Embedded SQL -- Cursors

Page 247: Db2

247

There are four steps in using a cursor:

1. Use DECLARE CURSOR to specify a cursor for result table.

2. Issue OPEN statement to begin cursor processing.3. Issue one FETCH statement for each row in result

table.4. Conclude cursor processing by issuing CLOSE

statement.

Embedded SQL -- Cursors

Page 248: Db2

248

Processing Multiple Rows

EMPNO LASTNAME000030000290000300

KWANPARKERSMITH

. DEFINE a CURSOR EXEC SQL DECLARE K9 CURSOR FOR SELECT EMPNO, LASTNAME FROM TEMPL WHERE DEPTNO = :DPT END-EXEC. . OPEN the CURSOR

EXEC SQL OPEN K9 END-EXEC. . FETCH RESULT ROWS ONE AT A TIME

EXEC SQL FETCH K9 INTO :EMPNO, :NAME END-EXEC. . CLOSE CURSOR when finished

EXEC SQL CLOSE K9 END-EXEC.

Loop untilbreak

Embedded SQL -- Cursors

Page 249: Db2

249

DECLARE CURSOR specifies what the results table should contain. It contains a SELECT statement where you name the columns you want to retrieve, the table that contains them, and the selection conditions for them.

Example: DECLARE CURSOR for retrieving instructor information for a course. EXEC SQL DECLARE INSTCURS CURSOR FOR SELECT DISTINCT PERSON.FNAME, PERSON.LNAME, OFFICE#, OFFICE_PHONE# FROM PERSON, TEACHER, SECTION WHERE SECTION.COURSE# = :COURSE-NUM AND PERSON.SSN = TEACHER.SSN AND SECTION .SSN = PERSON

END-EXEC.

CURSORS -- DECLARE CURSOR

Page 250: Db2

250

DECLARE CURSOR :

DECLARE CURSOR can be coded in WORKING-STORAGE or PROCEDURE DIVISION.

There are no INTO clauses in a DECLARE CURSOR’s SELECT statement.

Only need to declare a cursor once.

DB2 does not create the results table until SQL OPEN statement is executed for the table’s cursor.

CURSORS -- DECLARE CURSOR

Page 251: Db2

251

DECLARE CURSOR:

The SELECT statement in the DECLARE CURSOR statement simply specifies the characteristics of the result table that will be associated with the cursor.

Coding DISTINCT keyword in the SELECT component of aDECLARE CURSOR statement directs DB2 to exclude duplicate rows from the results table.

ORDER-BY statement allows you to sort the result table.

CURSORS -- DECLARE CURSOR

Page 252: Db2

252

Opening a cursor:

OPEN statement generates the results table associated with the cursor and positions the cursor just before the first row of the table.

EXEC SQLOPEN INSTCURS

END-EXEC.

OPEN is coded in the PROCEDURE DIVISION.

Embedded SQL -- Cursors

Page 253: Db2

253

Closing a Cursor

CLOSE statement releases the results table associated with the specified cursor.

EXEC SQLCLOSE INSTCURS

END-EXEC.

Closing a table is not required, since DB2 automatically closes all tables when the program ends. However, closing a table yourself allows you to release a substantial amount of memory the table uses and it allows you to re-open a table with out ending the program.

Embedded SQL -- Cursors

Page 254: Db2

254

Retrieving a row from a cursor-controlled results table:

Use the FETCH statement to retrieve a row from a results table that has a cursor.

EXEC SQLFETCH INSTCURSINTO :FNAME, :LNAME, :OFFICE#,

:OFFICE_PHONE#END-EXEC.

Evaluate the SQLCODE after each FETCH. When SQLCODE equals +100, you have reached the end of the result table (similar to end of file).

Embedded SQL -- Cursors

Page 255: Db2

255

EXEC SQL DECLARE CE CURSOR FOR SELECT...FROM EMP99; WHERE ... : :EXEC SQL OPEN CE;

EXEC SQL FETCH CE INTO...:

EXEC SQL DELETE FROM EMP99 WHERE CURRENT OF CE; : :EXEC SQL CLOSE CE:

Cursors-- DELETE via a CURSOR

Page 256: Db2

256

EXEC SQL DECLARE CX CURSOR FOR SELECT EMPNO, LASTNAME FROM EMP99 WHERE DEPTNO = :DPT FOR UPDATE OF LASTNAMEEND-EXEC. :EXEC SQL OPEN CX END-EXEC.

EXEC SQL FETCH CX INTO :EMPNO, :NAME END-EXEC. EXEC SQL UPDATE EMP99 SET LASTNAME = :NEWNAME WHERE CURRENT OF CX END-EXEC. :EXEC SQL CLOSE CX END-EXEC.

Cursors-- UPDATE via a CURSOR

Page 257: Db2

257

- Indicates successful end of a unit of work

- Changes to data will be written

- All PAGE LOCKS released

- TABLE(SPACE) LOCKS released if RELEASE

(COMMIT) on BIND

- CURSOR CLOSED

COMMIT

Embedded SQL -- Cursors

Page 258: Db2

258

COMMIT - CURSOR REPOSITIONINGEXEC SQL DECLARE C1 CURSOR FOR

SELECT X,Y,Z FROM T1

WHERE X >:STORX;

:

STORX = ' ';

S0:CTR = 0;

S1:EXEC SQL OPEN C1;

S2:EXEC SQL FETCH C1

INTO :STORX,:STORY,:STORZ;

/* If no update on this row, loop to S2 */

S3:EXEC SQL UPDATE T1

SET Y = :NEWY, Z = :NEWZ

WHERE X = :STORX; UPDATE current row

CTR = CTR+1;

IF CTR < 500 THEN GO TO S2;

ELSE EXEC SQL COMMIT;

GO TO S0;

Cursors-- CURSOR REPOSITIONING

Page 259: Db2

259

Cursors-- Read-Only CURSORS

Read-Only Cursors:•The SELECT statement contains:- FOR FETCH ONLY / FOR READ ONLY- ORDER BY; UNION or UNION ALL• The first SELECT contains- DISTINCT; a FUNCTION or EXPRESSION• The outer subselect contains GROUP BY / HAVING• The same table is used in SELECT statement and SUBQUERY• Select from multiple tables(join)• A nested table expression is used in the first FROM• Isolation UR is used without FOR UPDATE OF

UR + FOR UPDATE OF = CS

Page 260: Db2

260

Cursors-- Optimize for n Rows

EXEC SQL DECLARE C1 CURSOR FOR

SELECT . . .

OPTIMIZE FOR 20 ROWS

END-EXEC.

Used in online environment.Used to Improve performance.It is only used during the access path determination.It can NOT solve all your access performance problems.

Page 261: Db2

261

Cursors-- with RR/RS/CS/UR

EXEC SQL DECLARE C1 CURSOR FOR

SELECT . . .

WITH RR/RS/CS/UR

END-EXEC.

•Allows the override of package/plan isolation

•UR + FOR UPDATE OF = CS

•Can be used on a simple SELECT INTO

Page 262: Db2

262

Cursors-- keep update locks

EXEC SQL DECLARE C1 CURSOR FOR

SELECT . . .

WITH RR/RS KEEP UPDATE LOCKS

END-EXEC.

•Maintain X-lock(exclusive) on row/page even if the row was not updated

• Might reduce the possibilty of a deadlock

• If not used properly, it could reduce the degree of concurrency

Page 263: Db2

263

SELECT statement

In PROCEDURE DIVISION:

EXEC SQLSELECT column-specification,

[column-specification, …]INTO :host-var, [:host-var…]

:host-structureFROM table-name, [table-name,…][ WHERE selection-condition ]

END-SQL.

Embedded SQL -- Select

Page 264: Db2

264

column-specification

A description of what the SELECT statement should

put in the corresponding results table

EXEC SQLSELECT column-specification,

[column-specification, …]

Embedded SQL -- Select

Page 265: Db2

265

host-var

The COBOL host variable name into which DB2

will put the data for the corresponding column-

specification. Note that the host variable name is

preceded by a colon.

INTO :host-var, [:host-var…] :host-structure

host structure

The COBOL name of the group item into which DB2

will place the data it retrieves from the table.

Embedded SQL -- Select

Page 266: Db2

266

selection-condition

Specifies a test that SQL will apply to each row in

the table to determine whether to include it in the results

table.

[ WHERE selection-condition ]

Embedded SQL -- Select

Page 267: Db2

267

Example: Say you have the following FNAME data in the person table:

BOB GREENMARY WHITEJANE SMITH

To return the first and last name of a person with the first name “BOB”, you execute the statement:

EXEC SQLSELECT LNAME, FNAMEINTO :LNAME, FNAMEFROM PERSONWHERE FNAME = ‘BOB’

END-EXEC.When this SQL statement executes, it returns a one row results table:

BOB GREEN

Embedded SQL -- Select

Page 268: Db2

268

What if you had multiple “BOB”s and wanted to print them all? Then you would use a cursor defined as follows:

EXEC SQL DECLARE NAMEINFO CURSOR FOR SELECT FNAME, LNAME FROM PERSON WHERE

FNAME = “BOB”END-EXEC.

Then your SQL statement would be:

EXEC SQLFETCH NAMEINFOINTO :FNAME, :LNAME

END-EXEC.

Embedded SQL -- Select

Page 269: Db2

269

Ways to specify values for a results table in the SELECT clause

1. Unqualified column name.SELECT FNAME, LNAME

2. Qualified column name. SELECT PERSON.LNAME, MANAGER.LNAME

3. * -- All columns from a qualified source.SELECT *

4. Host variables. SELECT LNAME, FNAME, :COURSE#

Embedded SQL -- Select

Page 270: Db2

270

5. Literals.SELECT LNAME, FNAME, “is an Illinois resident.”

Adds the literal to the results table.

6. Computed Values.(shown on next slide)

7. USER keyword

SELECT USERExtracts the current user id from the DB2 catalog

and adds it to the results table.

Embedded SQL -- Select

Page 271: Db2

271

Computed Values.

Arithmetic expressions -- use a combination of host variables, column values and literals connected to each other with operators. The result is stored in the corresponding column of the results table.

** All items in arithmetic expressions must be numeric. **

SELECT LNAME, SALARY - :TAXCharacter data -- you can only combine, concatenate,

two or more base table columns using the || symbol.

SELECT FNAME || LNAME || ADDR || CITY || STATE || ZIP

Length of resulting column is the sum of lengths of elements.

Embedded SQL -- Select

Page 272: Db2

272

FROM clauseThe FROM clause specifies which base tables to include in the SQL processing. When two or more tables have a common column name, say SSN, then you must qualify the column name in the SELECT clause.

INTO clauseThe INTO clause of the SELECT statement names the COBOL host variables into which DB2 will place the results table data.

SELECT FNAME, LNAMEINTO :FIRST, :LAST

The data from FNAME will be placed into the host variable FIRST and data from LNAME will be put into LAST.

SELECT FNAME, LNAME FROM PERSON

Embedded SQL -- Select

Page 273: Db2

273

WHERE clause

The WHERE clause is used to specify a selection condition that identifies what rows DB2 should retrieve. This clause is optional.

Format of WHERE clause:

WHERE expression1 operator expression2

Example: WHERE SALARY < :MAXSAL

The possible operators are: <, >, <=, >=, = , <> (not equal)Enclose literal in quotation marks if of character type, but not numeric.

WHERE FNAME = “BOB”

Embedded SQL -- Select

Page 274: Db2

274

WHERE ……. IN -- Specifies a list of items, one of which the value in the comparison item must match for the condition to be met.Commas separate the values, parentheses surround the list. The list can be made up of host variables, column names, functions, calculated values and USER keyword.Character literals require quotation marks.

EXEC SQLSELECT SSNINTO :SSNFROM TRANSCRIPTWHERE COURSE# IN (240, 241, 330, 360)

END-SQL

You can also combine IN with the NOT keyword: WHERE COURSE# NOT IN (465, 466, 467)

Embedded SQL -- Select

Page 275: Db2

275

BETWEEN -- Specifies a beginning and ending value for a range of values that the comparison item’s value must fall with in order for the condition to be met.

The lower (min) limit is coded before the upper (max) limit.

WHERE LNAME BETWEEN “R” AND “S”

“ROY” would meet this condition.

Range limits are inclusive, if someone had the last name “S”, they would be included in the results table. You can use host variables, column names, functions, calculated values, USER keyword, and numeric literals (such as BETWEEN 10 AND 100).

NOT can also be used with BETWEEN.

Embedded SQL -- Select

Page 276: Db2

276

LIKE -- Specifies a “fuzzy” value. The value of the comparison item must be similar to this value for the condition to be met.

WHERE column-name [NOT] LIKE character-mask

Character Mask - a pattern of characters that DB2 uses to evaluate contents of columns. A mask can be a literal, a host variable, or USER keyword. Can only compare character data, hence a character mask. The mask can have special characters to represent unknown characters.

Underscore ( _ ) -- means that any single character can be in this position in the column value and still match the mask. Percent ( % ) -- means that any number of characters, including zero, can be in this position in the column value and still match the mask.

Embedded SQL -- Select

Page 277: Db2

277

Complex selection conditions with AND, OR, and NOT

You can use AND, OR and NOT to combine selection conditions in the where clause. For example:

WHERE PERSON.SSN = TRANSCRIPT.SSN AND ( COURSE# = 240 OR COURSE# = 360 )

The where condition will be met if the PERSON table’s SSN matches the TRANSCIPT table’s SSN and the COURSE# iseither 240 or 360.

Parentheses allow you to specify the order in which the condition is evaluated.

Embedded SQL -- Select

Page 278: Db2

278

FunctionsColumn functions yield a single value that results from manipulating or evaluating data in one column through a number of rows.

SUM( numeric-column-name)AVG( numeric-column-name)MIN(column-name)MAX(column-name)COUNT( * )DISTINCT column-name

When you use a basic column function in a select clause, DB2 returns a one-row result table. If you use DISTINCT with COUNT, DB2 doesn’t count duplicates. Rows of nulls are not considered by functions -- zeroes and spaces are not nulls. You can specify more than one function on a single statement.

Embedded SQL -- Select

Page 279: Db2

279

GROUP-BY (HAVING) clauseGROUP-BY -- DB2 collects rows that meet the selection condition into groups where each row has the same value in the column specified in the GROUP-BY clause. If a HAVING clause is coded in the GROUP-BY, DB2 then takes each group and applies the column function to it. This creates a multi-row results table where each row contains the result of the column function for each group.

The following will retrieve the students last names and GPA, and order them by LNAME.

SELECT LNAME, GPA FROM PERSON, STUDENT

WHERE PERSON.SSN = STUDENT.SSN GROUP BY LNAME

Embedded SQL -- Select

Page 280: Db2

280

The following code retrieves course numbers and grades for those courses, groups them by the course# and then, for each course#, calculates the average grade. The results table is a multi-row table where each row has the average grade for a class.

SELECT COURSE.COURSE#, GRADE FROM COURSE, TRANSCRIPT

WHERE COURSE.COURSE# = TRANSCRIPT.COURSE# GROUP BY COURSE#

HAVING AVG(GRADE)

Embedded SQL -- Select

Page 281: Db2

281

Testing return codes:

EXEC SQL ...... END-EXEC.IF SQLSTATE NOT = ‘00000’ CONTINUE IF SQLSTATE IS = ‘02000’ GO TO NOMORE ELSE IF SQLSTATE > ‘01000’ AND SQLSTATE < ‘02000’ THE GO TO WARNSQL ELSE GO TO ERRORSQL.

ERROR HANDELING -Testing Return Codes

Page 282: Db2

282

. Conditions:

SQLERROR

- negative SQLCODE

SQLWARNING

- positive SQLCODE(not+100)

- or SQLWARN0 = 'W'

NOT FOUND

- SQLCODE = +100

. Actions:

GO TO :X

- control transferred to statement labeled X

CONTINUE

- program continues with next statement

- used to cancel effect of prior WHENEVER

EXEC SQL WHENEVER condition actionEND-EXEC.

WHENEVER' STATEMENT

Error Handling- WHENEVER STATEMENT

Page 283: Db2

283

: SQL statement :EXEC SQLWHENEVER SQLERROR GO TO :A END-EXEC. : SQL statement IF SQLCODE < 0 A : SQL statement IF SQLCODE < 0 A :EXEC SQLWHENEVER SQLWARNING GO TO :W END-EXEC.EXEC SQLWHENEVER SQLERROR GO TO :B END-EXEC. : SQL statement IF SQLCODE < 0 B IF warning W:

EXAMPLE

Error Handling- WHENEVER STATEMENT

Page 284: Db2

284

Error Handling- Error Message Formating Routine

CALL ‘DSNTIAR’ USING sqlca message irecl

DSNTIAR routine takes data from the SQLCA, formats it into a message, and places the result in a message output area that you provide in your application program. Each time you use DSNTIAR, it overwrites any previous message.NOT to invoke DSNTIAR unless an error condition is detected because the module is dynamically loaded into storage when invoked.

Page 285: Db2

285

Error Handling- General

•WHENEVER should not be used-Different treatment needed for NOT FOUND after DELETE /UPDATE/INSERT-Coming back after WHENEVER?-Might want to intercept other return code

•SYSDAM will normally provides a STANDARDIZED error routine for every one to use

•Only CALL DSNTIAR in error condition

Page 286: Db2

286

Error Handling- Indicator Variables

10 P-PHONE PIC X(4).10 P-PHONE-I PIC S9(4) COMP....EXEC SQL SELECT PHONENO INTO :P-PHONE:P-PHONE-I FROM EMP WHERE EMP_NO = :EMP-NOEND-EXEC.

After SELECT:

If PHONENO contains a NULL value:P-PHONE -> unchanged P-PHONE-I -> negative

If PHONENO contains data:P-PHONE -> undated P-PHONE-I -> not negative

Page 287: Db2

287

Error Handling- Indicator Variables

RetrievingInserting NULL valuesSelecting on

Generate Null Indicator Structure by DCLGEN:

01 PEMPL-IND PIC S9(4) OCCURS 6 TIMES.

PAGE:4-17

Page 288: Db2

288

Error Handling- Indicator Variables

Indicator Variable Values

0

+n

-n

-2

Zero denotes that value in data variable area is not null.

Any positive number indicates truncation of a string value, where ‘n’ is the length of the original string(string field only).Any negative number indicates a NULL value in the data variable.

Negative 2 indicates a NULL value in the data variable because of either a numeric conversion error or an arithmetic expression error

Page 289: Db2

289

Error Handling- Other Error Conditons

DEACLOCK and Timeout 40001/-911 Automatic Rollback 57033/-913 No

TABLE CHECK Constraint 23513/-545

VIEW CHECK OPTION 23501/-161

DATE invalid 22007/-180 or -181

Page 290: Db2

290

//I14761C JOB F313,CHUANG,NOTIFY=I14761,

// MSGCLASS=X,CLASS=2,MSGLEVEL=(1,1),REGION=2048K

//*----- PRECOMPILE, COMPILE, LINKEDIT COB2 PGRM --------

//COMPILE EXEC PROC=TDB85CMP,MBR=MIRFT5

//PC.SYSIN DD DSN=BDVLP.F313.SOURCE(MIRFT5),DISP=SHR

//LKED2.SYSLMOD DD DSN=BDVLP.F313.LOAD(MIRFT5),DISP=SHR

//LKED2.SYSIN DD *

INCLUDE SYSLIB(DSNELI)

/*

//*------ BIND PACKAGE -----------------

//BINDPACK EXEC PGM=IKJEFT01,DYNAMNBR=20

//STEPLIB DD DSN=DB2T.DSN510.SDSNLOAD,DISP=SHR

//DBRMLIB DD DSN=BDVLP.DBRM.LIB,DISP=SHR

//SYSDUMP DD SYSOUT=*

//SYSTSPRT DD SYSOUT=*

//SYSPRINT DD SYSOUT=*

//SYSTSIN DD *

DSN SYSTEM(DSN1)

BIND PACKAGE(MI) MEMBER(MIRFT5) ACTION(REPLACE) -

QUALIFIER(MI) VALIDATE(BIND)

END

/*

DB2--COMPILE JCL EXAMPLE

Page 291: Db2

291

//EDUCS99R JOB 'PROD.PSJOB.JCL',MSGLEVEL=(0,0),

// CLASS=V,MSGCLASS=Q,TIME=1440,REGION=4096K

//JOBDD1 INCLUDE MEMBER=JOBDDP

//IPU155 EXEC PGM=IKJEFT01,DYNAMNBR=20,COND=(4,LT)

//SDDOCF DD DSN=DO.SDDOCF.PS,DISP=SHR

//VEIPS1 DD DSN=IP.VEIPS1.VE,DISP=SHR

//SORTWK01 DD UNIT=DWORK,SPACE=(CYL,(20,5),RLSE)

//SORTWK02 DD UNIT=DWORK,SPACE=(CYL,(10,5),RLSE)

//SORTWK03 DD UNIT=DWORK,SPACE=(CYL,(10,5),RLSE)

//SYSTSPRT DD SYSOUT=*

//SYSPRINT DD SYSOUT=*

//SYSUDUMP DD SYSOUT=*

//SYSOUT DD SYSOUT=*

//SYSTSIN DD *

DSN SYSTEM(DSN1)

RUN PROGRAM(IPU155) PLAN(PLANIP) -

LIB('PROD.PSBATCH2.LOAD')

END /*

DB2--COMPILE JCL EXAMPLE

Page 292: Db2

292

EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL INCLUDE AAM1RCD END-EXEC. EXEC SQL DECLARE AA11SEL CURSOR (WITH HOLD) FOR SELECT * FROM AA.TBAAM1 WHERE ACCP_CODE_AAM1 = :ACCP-CODE-AAM1 AND PUT_AP_AAM1 = :PUT-AP-AAM1 FOR FETCH ONLY WITH UR END-EXEC.

EXEC SQL DECLARE AA11SEL1 CURSOR FOR SELECT * FROM AA.TBAAM1 WHERE ACCP_CODE_AAM1 = :ACCP-CODE-AAM1 AND VCHR_NO_AAM1 = :VCHR-NO-AAM1 AND PUT_AP_AAM1 = :PUT-AP-AAM1 FOR UPDATE OF VCHR_NO_AAM1,PUT_AP_AAM1 END-EXEC.

EXEC SQL OPEN AA11SEL END-EXEC. IF SQLCODE NOT = ZERO MOVE '*' TO ERR-MARK DISPLAY PROGRAM-ID-MVS 'TBAAM1 OPEN FAIL,SQLCODE= ' SQLCODE GO TO 220-END-GET-D02SEG.

DB2-- COBOL CODE EXAMPLE

Page 293: Db2

293

220-GET-TBAAM1. EXEC SQL FETCH AA11SEL INTO :DCLTBAAM1 END-EXEC. IF SQLCODE = 100 EXEC SQL CLOSE AA11SEL END-EXEC GO TO 220-END-GET-D02SEG.IF SQLCODE NOT = ZERO MOVE '*' TO ERR-MARK DISPLAY PROGRAM-ID-MVS 'TBAAM1 FETCH FAIL,SQLCODE= ' SQLCODE EXEC SQL UPDATE AA.TBAAM1 SET VCHR_NO_AAM1 = :VCHR-NO-AAM1, PUT_AP_AAM1 = :PUT-AP-AAM1 WHERE CURRENT OF AA11SEL1 END-EXEC.EXEC SQL SELECT COUNT(*) INTO : CONT-WK FROM ST.TBSTC3 WHERE ( ORDER = :ORD-NO-SAVE) END-EXEC.IF CONT-WK NOT > ZERO GO TO 500-CLOSE-STC3SEL

DB2-- COBOL CODE EXAMPLE

Page 294: Db2

294

1 、 TIMESTAMP DISPLAY FORMAT , 26 BYTES :

01 SEQ-WK-FMT. 10 FILLER PIC X(4) VALUE ’1995’. 10 FILLER PIC X VALUE ’-’. 10 FILLER PIC X(2) VALUE ’01’. 10 FILLER PIC X VALUE ’-’. 10 FILLER PIC X(2) VALUE ’01’. 10 FILLER PIC X VALUE ’-’. 10 FILLER PIC X(2) VALUE ’01’. 10 FILLER PIC X VALUE ’.’. 10 FILLER PIC X(2) VALUE ’01’. 10 FILLER PIC X VALUE ’.’. 10 FILLER PIC X(2) VALUE ’01’ 10 FILLER PIC X VALUE ’.’. 10 FILLER PIC X(6) VALUE ’000001’.

DB2-- COBOL CODE EXAMPLE(TIMESTAMP)

Page 295: Db2

295

DB2-- COBOL CODE EXAMPLE(TIMESTAMP)

2 、 CODES :

1. SELECT COIL_NO_P, ST_NM_P, SEQ_P

FROM ID.TBIDPF

WHERE COIL_NO_P LIKE ‘271%’ AND

(CHAR(SEQ_P) LIKE ‘1997-10%’ )

ORDER BY COIL_NO_P;

2. SELECT COIL_NO_P, ST_NM_P, SEQ_P

FROM ID.TBIDPF

WHERE COIL_NO_P LIKE ‘271%’ AND

(CHAR(SEQ_P) LIKE ‘1997-10-09%’)

ORDER BY COIL _NO_P;

3. SELECT COIL_NO_P, ST_NM_P, SEQ_P

FROM ID.TBIDPF

WHERE COIL_NO_P LIKE ‘271%’ AND

SEQ_P >= ‘1997-10-09-01.01.01.000001’)

ORDER BY COIL _NO_P;

4. CHAR function:Change timestamp to string for LIKE use

EXAMPLE: (CHAR(SEQ_P) LIKE ‘1997-10-09%’)

Page 296: Db2

296

DB2-- COBOL CODE EXAMPLE(PageUp/PageDown)EXEC SQL DECLARE IPMASEL CURSOR FOR

SELECT PROD_CODE_IPMA,ACCT_ITEM_IPMA,CC_IPMA,

WCE_IPMA,SUM(QTY_D_IPMS),SUM(QTY_M_IPMA)

FROM IP.TBIPMA

WHERE (PROD_CODE_IPMA >= :PROD-CODE-IPMA)

AND NOT (PROD_CODE_IPMA = :PROD-CODE-IPMA AND

ACCT_ITEM_IPMA < :ACCT-ITEM-IPMA)

AND NOT (PROD_CODE_IPMA = :PROD-CODE-IPMA AND

ACCT_ITEM_IPMA = :ACCT-ITEM-IPMA AND

CC_IPMA < :CC-IPMA)

AND NOT (PROD_CODE_IPMA = :PROD-CODE-IPMA AND

ACCT_ITEM_IPMA = :ACCT-ITEM-IPMA AND

CC_IPMA = :CC-IPMA AND

WCE_IPMA < :WCE-IPMA)

AND (YYMM_IPMA BETWEEN :YYMM-FM-WK AND

:YYMM-TO-WK)

GROUP BY PROD_CODE_IPMA,ACCT_ITEM_IPMA,CC_IPMA,WCE_IPMA

OPTIMIZE FOR 15 ROWS FOR FETCH ONLY WITH UR

END-EXEC.

Page 297: Db2

297

DB2 --DB2应用开发的步骤

了解所需的DATA

GROUP

DESIGNTABLE

CREATEDB,TS,TB,

IDX

CREATEPLAN ID( 与其他系统连接否? )RCT

CODING创建 TEST TABLE用 SPUFI 测试 CODE 中 SQL COMMAND 执行结果是否正确?在 SPUFI中使用 EXPLAIN了解是否使用 INDEX ,是否需新建 INDEX

RUNSTATS?

GRANTTABLE

TO PUBLIC

Page 298: Db2

298

STATIC SQL

-Can be used if the statement’s•TYPE•TABLES•COLUMNS•WHERE-clause

are known when you write your program.

-The complete SQL statements is contained in the program,

except perhaps for host-variables referring to COLUMN values

-BIND creates the access path.

-Only the EXECUTE privilege is checked before execution of

the access path.

DB2-Dynamic SQL

Page 299: Db2

299

DB2-- Dynamic SQL

Dynamic SQL

-Must be used if anything other than COLUMN values are

unknown at program preparation.

-The statement is contained in a host variable.

-BIND cannot create an access path but an ‘empty’ package

will be created

-Security is checked at execution time when access path is

created.

Page 300: Db2

300

DB2-- Dynamic SQL

Dynamic SQL Statements Types:

1. NO-SELECT statement

•Complete

•Parameterized

2. SELECT statement

•Fixed SELECT list

•Varying SELECT list

3. UNKONW statement

Page 301: Db2

301

DB2-- Dynamic SQL

NO-SELECT statement Examples:

01 STMT.

49 STMT-LENGTH PIC S9(4) COMP VALUE +255.

49 STMT-TEXT PIC X(255).

.....

MOVE ‘DELETE FROM EMP’ TO STMT.

EXEC SQL EXECUTE IMMEDIATE :STMT

END-EXEC.

Page 302: Db2

302

DB2-- Dynamic SQL

Parameterized NO-SELECT statement Examples:

DELETE FROM EMP WHERE DEPNO=?AND HIREDATE=?

STMT

EXEC SQL PREPARE PRST FROM :STMT END-EXEC.Check SQLCA ...

D17 1994-11-1X Y

EXEC SQL EXECUTE PRST FROM :X, :Y END-EXEC.Check SQLCA ...

Page 303: Db2

303

DB2-- Dynamic SQL

SELECT statement with Fixed List Examples:

SELECT LASTNAME, PHONENO FROM EMP WHERE HIREDATE>?

STMT

EXEC SQL DECLARE C1 CURSOR FOR PRST END-EXEC.EXEC SQL PREPARE PRST FROM :STMT END-EXEC.Check SQLCA ...

1994-11-1X

EXEC SQL EXECUTE PRST FROM :X END-EXEC.Check SQLCA ...EXEC SQL OPEN C1 END-EXEC.EXEC SQL FETCH C1 INTO :NAME, :PHONE END-EXEC....EXEC SQL CLOSE C1 END-EXEC.

Page 304: Db2

304

DB2-- Dynamic SQL

SELECT statement with Varying List

SELECT COL1,COL2 FROM EMP STMT

EXEC SQL INCLUDE SQLDA END-EXEC.EXEC SQL DECLARE C1 CURSOR FOR PRST END-EXEC.

Set SQLNEXEC SQL PREPARE PRST FORM :STMT END-EXEC.EXEC SQL DESCRIBE PRST INTO :SQLDA END-EXEC.Check SQLCA AND SQLDA:IF SQLD = 0 THEN EXECUTE PRST ...IF SQLN < SQLD THEN ... -allocate larger SQLDA of 16 +(SQLD*44) bytes -set SQLN to SQLD -DESCRIBE PRST

Page 305: Db2

305

DB2-- Dynamic SQL

SELECT statement with Varying List

... Allocate storage for results

... Place addresses into SQLDAEXEC SQL OPEN C1 END-EXEC.EXEC SQL FETCH C1 USING DESCRIPTOR :SQLDAEND-EXEC.... Check SQLCA... Process... Branch back to FETCH ( UNTIL SQLCODE=+100)EXEC SQL CLOSE C1 END-EXEC.

Page 306: Db2

306

DB2-- Dynamic SQL Summary

SUMMARY

Coding

EXECUTE IMMEDIATE

PREPARE/EXECUTE

PREPARE/DESCRIBEFETCH

Statements supported

Complete Non-SELECT

Parameterized Non-SELECT

SELECT with fixed select list

Complete SELECT with variable

select list or fixed select listUnknown SQL

Page 307: Db2

307

Page 308: Db2

308

DB2 EXPLAIN Function

Explain Function is used for

• detailing the access paths chosen by DB2 optimizer for SQL statements

• performance monitoring

• determining the work done by DB2 “behind the scenes”

• whether or not DB2 uses the indexes and how

• the order in which the tables are accessed

• whether or not a sort was needed

• tablespace locking requirements

• performance of an SQL statement based upon access paths chosen

Page 309: Db2

309

 USER :CREATES userid.PLAN_TABLE

Invokes EXPLAIN

DB2 :INSERTs rows into PLAN_TABLE

 

Invoking EXPLAIN 

•SQL EXPLAIN statement

EXPLAIN PLAN | ALL SET QUERYNO = n

FOR SQL-STATEMENTS

•BIND or REBIND OPTION

EXPLAIN YES | NO on DB2I BIND panel

ADD EXPLAIN(YES) OPTION TO BIND COMMAND

DB2 EXPLAIN Function- USING EXPLAIN

Page 310: Db2

310

DB2 EXPLAIN Function

How EXPLAIN works:

a single SQL statement OR

a series of SQL statements

are passed through the DB2 optimizer, and the access paths that DB2 chooses are externalized, in coded format into a PLAN_TABLE

The PLAN_TABLE is nothing more than a standard DB2 table that must be defined with predetermined columns, data types, and lengths.

Page 311: Db2

311

DB2 EXPLAIN Function -- PLAN_TABLE

CREATE TABLE PLAN_TABLE (QUERYNO INTEGER NOT NULL , QBLOCKNO SMALLINT NOT NULL , APPLNAME CHAR(8) NOT NULL , PROGNAME CHAR(8) NOT NULL , PLANNO SMALLINT NOT NULL , METHOD SMALLINT NOT NULL , CREATOR CHAR(8) NOT NULL , TNAME CHAR(18) NOT NULL , TABNO SMALLINT NOT NULL , ACCESSTYPE CHAR(2) NOT NULL , MATCHCOLS SMALLINT NOT NULL , ACCESSCREATOR CHAR(8) NOT NULL , ACCESSNAME CHAR(18) NOT NULL , INDEXONLY CHAR(1) NOT NULL , SORTN_UNIQ CHAR(1) NOT NULL , SORTN_JOIN CHAR(1) NOT NULL , SORTN_ORDERBY CHAR(1) NOT NULL , SORTN_GROUPBY CHAR(1) NOT NULL , SORTC_UNIQ CHAR(1) NOT NULL , SORTC_JOIN CHAR(1) NOT NULL , SORTC_ORDERBY CHAR(1) NOT NULL , SORTC_GROUPBY CHAR(1) NOT NULL , TSLOCKMODE CHAR(3) NOT NULL , TIMESTAMP CHAR(16) NOT NULL , REMARKS VARCHAR(254) NOT NULL , PREFETCH CHAR(1) NOT NULL ,

COLUMN_FN_EVAL CHAR(1) NOT NULL WITH DEFAULT,

MIXOPSEQ SMALLINT NOT NULL WITH DEFAULT,

VERSION VARCHAR(64) NOT NULL WITH DEFAULT,

COLLID CHAR(18) NOT NULL WITH DEFAULT,

ACCESS_DEGREE SMALLINT , ACCESS_PGROUP_ID SMALLINT , JOIN_DEGREE SMALLINT , JOIN_PGROUP_ID SMALLINT , SORTC_PGROUP_ID SMALLINT , SORTN_PGROUP_ID SMALLINT , PARALLELISM_MODE CHAR(1) , MERGE_JOIN_COLS SMALLINT , CORRELATION_NAME CHAR (18), PAGE_RANGE CHAR (1) NOT NULL, JOIN_TYPE CHAR (1) NOT NULL, GROUP_MEMBER CHAR (8) NOT NULL, IBM_SERVICE_DATA VARCHAR (254) NOT

NULL, WHEN_OPTIMIZE CHAR (1) NOT NULL, QBLOCK_TYPE CHAR (6) NOT NULL, BIND_TIME TIMESTAMP NOT

NULL ) IN IBMDB001.IBMTS001;

Page 312: Db2

312

DB2 EXPLAIN Function -- PLAN_TABLE

000402 -- CLASS EXPLAIN DEMO - TO WALK THRU SOME QUERIES AND 000403 -- EXPLAIN RESULTS 000404 -- 000720 -- STEP 1: CREATE PLAN TABLE TO USE IF ONE DOESN'T ALREADY

EXIST 000730 -- IF YOU GET AN ERROR SAYING THE TABLE ALREADY EXISTS 000731 -- CHANGE THE CREATE LINES INTO COMMENTS BY 000732 -- PUTTING -- IN 1ST 2 COLUMNS AND RERUN 000733 -- 000734 -- CREATE TABLE PLAN_TABLE 000735 -- LIKE T90KAD1.PLAN_TABLE 000736 -- IN IBMDB001.IBMTS001; 000737 --

Create the PLAN_TABLE using one already available

Page 313: Db2

313

DB2 EXPLAIN Function -- PLAN_TABLE

000738 EXPLAIN PLAN SET QUERYNO = 51 FOR 000739 SELECT FNAME, LNAME, ADDRESS 000740 FROM PERSONY 000750 WHERE SSN = ?; 000760 -- 000770 -- SQL TO EXAMINE PLAN TABLE FOR QUERY 000780 -- 000790 -- 000800 SELECT QUERYNO,PLANNO,METHOD,TNAME,ACCESSTYPE, 000900 MATCHCOLS,INDEXONLY,PREFETCH,TSLOCKMODE,

ACCESSNAME 001000 FROM PLAN_TABLE 001100 WHERE QUERYNO = 51 001200 ORDER BY PLANNO; 001210 --

To examine the access paths of a query:

1. Issue “EXPLAIN” for the SELECT

2. Use SQL to SELECT appropriate fields from PLAN_TABLE

Page 314: Db2

314

DB2 EXPLAIN Function -- PLAN_TABLE

Output of previous SELECT on PLAN_TABLE

Page 315: Db2

315

DB2 EXPLAIN Function -- PLAN_TABLE

Another Example:

Page 316: Db2

316

DB2 --RUNSTATS

DB2 makes its access path selection at BIND time, based upon certain statistical

information in the DB2 catalog. This information is gathered by the

RUNSTATS Utility.

 RUNSTATS Do:

. EXAMINES TABLES and INDEXES

. ENTERS STATISTICS INTO THE CATALOG

# of table rows

# of pages occupied by data

# of keys in an index

“clustered” indicator for an index

Range of key values in an index

. IS DBA RESPONSIBILITY, it can provide the DBA information about

space and freespace usage.

Page 317: Db2

317

DB2 --BIND COMMAND EXAMPLE

   BIND COMMAND EXAMPLE DSN SYSTEM(DSN) BIND PACKAGE(IS) MEMBER(ISOUBD) ACTION(REPLACE) - QUALIFIER(IS) VALIDATE(BIND) OWNER(I11177) EXPLAIN(YES) END

Page 318: Db2

318

DB2 Utilities -- Overview

Two types of utilities in DB2:

online utilities and stand-alone utilities

Online Utilities run as standard MVS batch jobs. They require DB2 to be running. They DO NOT run under the control of the terminal monitor program. They have their own attach mechanisms.

Stand-alone Utilities execute as batch jobs independent of DB2. They can be invoked only by means of MVS JCL.

Page 319: Db2

319

DB2 Utilities -- Overviewlog RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address.

Page 320: Db2

320

DB2 Utilities -- Overviewlog RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address.

Page 321: Db2

321

DB2 Utilities -- Overview

REORG - reorganizes various DB2 and user tablespace

CHECK - checks whether or not indexes are consistent with the data that they invoke and issues warning messages when it finds an inconsistency.

DIAGNOSE - used to generate information used in diagnosing certain problems that may occur in DB2.

LOAD - used to load data into one or more tables that reside in a tablespace or partition.

MODIFY - used to delete unwanted copies from the SYSIBM.SYSCOPY catalog tables and records of related log records form the SYSIBM.SYSLGRNG directory.

Page 322: Db2

322

DB2 Utilities -- Overview

QUIESCE - establishes a quiesce point (the current RBA) for one or more tablespaces that have associated referential integrity dependencies and records in the SYSIBM.SYSCOPY DB2 Catalog table. This provides a point from which to recover effectively and correctly all related tablespaces within a referentially integrated group of table.

REPAIR - used to repair data and is to be used only in very controlled or extreme circumstances. Improper use can cause even further damage.

Page 323: Db2

323

DB2 Utilities -- Overview

REPORT - produces reports about tablespaces containing the following: RECOVERY history

Log rangesArchive data set volume serial numbersNames of all tablespaces and tables in a

tablespace set.

RUNSTATS - used to scan a tablespace or indexes to gather information about utilization of space and efficiency or indexes.

STOSPACE - used to update DB2 catalog columns that tell how much space is allocated for storage groups.

Page 324: Db2

324

DB2 Utilities -- Overviewlog RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address.

Page 325: Db2

325

DB2 Utilities -- Overviewlog RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address. log RBA -Each byte in the DB2 log is addressable by its offset from the beginning of the log, and that offset is known as its relative byte address.

Page 326: Db2

326

DB2 Service Aids -- Overview

DSN1PRNT - used to print out any DB2 data page

DSN1COPY - allows the following to be performed

copy DB2 VSAM data sets to sequential data setscopy sequential data sets to VSAM data setscopy VSAM to other VSAMcopy sequential to other sequential data setsOBID translation when copying DB2 VSAM to another

DB2 VSAMprints hexadecimal dumps of DB2 data setsperform validity checking on data or index pages

DSN1LOGP - reads and formats DB2 recovery log for display.

DSN1CHKR - used to verify that the integrity of DB2 catalog and directory tablespaces has not been compromised

Page 327: Db2

327

Query Management Facility

Page 328: Db2

328

Query Management Facility

Benefits:

• can produce professional looking reports easily

• requires no coding of programs

• can be guided through a selection of data to use on the report OR can enter SQL directly

• has multiple ways to formulate a query

1. SQL 2. Prompted query mode 3. QBE (Query By Example)

Page 329: Db2

329

Query Management Facility

Users of QMF:

• Users to find information and to create reports

• Developers to try out statements to be used in programs

• Developers to create customized reports

• Developers to check results of program updates during testing

• DBAs to monitor the databases, etc.

Page 330: Db2

330

Query Management FacilityQuery Management Facility

Option 3 on Miscellaneous Programs of TSO

QMF is used for producing nicely formatted reports from DB2 databases.

Page 331: Db2

331

Query Management Facility -- Home Panel

Page 332: Db2

332

Query Management Facility

DB2

Tables

The Query

Result Data

Form Panels

Report

The data is retrieved from the tables via the query. The result of the query is used in the forms to produce a report.

Page 333: Db2

333

Query Management Facility -- Designing Reports

Enter a Query

Run the Query

View the

Report

OK?yes

Print the Report

no

Modify the

Report

ORModify

the Query

Page 334: Db2

334

Query Management Facility -- Report Panel (PF2)

PF4: Print

PF6: Go back to query

PF7: Scroll Back

PF8: Scroll Forward

PF10: Scroll Left

PF11: Scroll Right

Page 335: Db2

335

Query Management Facility -- Report Layout

Page Heading

Column Headings

Detail Lines

.

.

.

.

.Final Footing Line (on last page)

Page Footing

Page 336: Db2

336

==END==