SlideShare a Scribd company logo
1 of 336
DB2 UDB for z/OS Application Programming Workshop Wu Chi 027- 87544884 [email_address]
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.
DB2 Slides -- Index Topic 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
DB2 Family
DB2 Product Components
 
Introduction ,[object Object],[object Object],[object Object],[object Object],[object Object]
End-User’s View They See tables & issue SQL DML statements Don’t see other programs; Don’t worry about data integrity, and so on
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
DML language SELECT * FORM EMP  WHERE EMPNO=‘000010’ UPDATE INSERT DELETE
Static end users Use specific programs(transactions) to perform specific actions on DB2 data. Need not knonw SQL, DB2
The Static Program’s View Contain built-in or embedded SQL statements At execution time, those SQL statements will be executed by Loading the needed access paths into storage and  Completing the missing variables with input from a dataset or terminal. The access path is determined at compilation time, the access logic will always be the same.
The Dynamic Program’s View Don’t have complete built-in SQL statements but ask for the SQL statements(or parts of SQL statements such as a WHERE clause) at Execution Time. The access path could not be determined at compilation time since a fundamental part of the statement, or the entire  statement, was until execution of the program.
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 for administration . DB2 environment setup need only once. Additional advantage: portability
The Internet User’s View Access DB2 without being aware of this fact. Net.data  provides the user with the link between the Web page and the database.
Program’s View- General Each program accesses tables as if it were the only one to do so. Doesn’t worry about: integrity, concurrency
Program’s Responsibility: LUW(Logical Unit of Work) A  2000  1000  1000  1000 B  3000  3000  4000  4000 A  2000  1000  1000  2000 B  3000  3000  4000  3000 Transfers $1000 from account A to account B LUW UPDATE  A UPDATE  A UPDATE  B UPDATE  B COMMIT ROLLBACK
Program’s Responsibility: Checkpoint / Restart LUW LUW LUW LUW LUW LUW LUW LUW
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
The System’s View DB2’S Responsibilies SECURITY CONSISTENCY CONCURRENCY PERFORMANCE METADATA
The  DB2 Family MAINFRAME servers LAN clients
ROLES and Interfaces in DB2
Application Life Cycle
TSO Time Sharing Option Logging on & ISPF Initialization
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:
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 TSO sessions after  this will begin  with this ISPF screen after the initial logon.
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>.
Next:  Type ‘2’ at the Option prompt of the Utility  Selection Panel then <ENTER>
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’
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.
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.
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’
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
The screen below is the result of the ‘S’ request on the ALTTAB member. Z999999.DB2.SPUFI (ALTTAB)
NOW to get to DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous  programs.
Then from the next menu choose option ‘2’ -- DB2I.  Now you can start learning DB2!
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Logging off of TSO To end a session of TSO, press F3 until you reach the “Specify Disposition of Log Data Set” panel.
Type ‘2’ to delete  without printing Then press <ENTER> to choose SYSOUT class A  and exit ISPF
Then at the READY  prompt, type either LOGOFF to terminate your session or type ISPF to return to ISPF main menu
DB2
[object Object],[object Object],[object Object],Interactive :   Customer Information Control System (CICS) Information Management System (IMS)  Time Sharing Option (TSO) and DB2I Application Programming   :   COBOL DB2  ( D ata b ase  2 )
DB2I   TOPICS  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],SPUFI  ( S QL  P rocessor  U sing  F ile  I nput) Terminal user SPUFI DB2 Output (print) data set Tables Input  data set
To get to SPUFI in DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous  programs.
Then from the next menu choose option ‘2’ -- DB2I.  Now  type a ‘1’ at the “DB2I PRIMARY OPTION MENU
SPUFI’s Main Menu consists of three sections:   1.  Information about the input data set 2.  Information about the output data set 3.  Processing Options (steps SPUFI works through) NOTE:  The F1 help of SPUFI is NOT available.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Input data set Data set type:   Sequential or partitioned Allocation:   Must be already allocated Record size:   79 or 80 characters
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Output (print) data set Data set type:  Sequential Allocation:  May be allocated dynamically Record size:  80 character minimum (4092 is the default)
If you press <ENTER> after supplying the input and output data 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. **
Change Defaults  (leave this set to ‘NO’): The change defaults panel allows you to change any of nine options that relate to the processing of input data sets and  the format of the resulting output of that  processing.
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:
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.
MAX NUMERIC FIELD  -- maximum width a numeric column of a 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.
Edit Edit 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.
‘ 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.
Pressing F3 during an EDIT session will accept the new  input file and return to the SPUFI main menu to execute the next step. ‘ USERID.DB2.SPUFI(SQLPGM)’  PRESS ‘F3’ ‘ USERID .DB2.SPUFI(SQLPGM)’
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.
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.
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.
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.)  ,[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],Output of SQL Statements ,[object Object],[object Object],Attribute Names Data in RESULT dataset
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.
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.
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:
SQL statements allowed under SPUFI ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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.
[object Object],[object Object],[object Object],[object Object],Example 1 continued
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>.
Press  <ENTER>  to go to EXECUTE Example 1 continued
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.
Example 2:
This is the output from two screens combined.  Example 2 continued
Example 3: The SQL dataset The Output dataset with the “Count” Displayed
DB2 Class Example
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 )
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
PERSON STUDENT TEACHER Relations in Example Database
COURSE SECTION
TRANSCRIPT
Query 1 Query 2
Query 3
Query 4
Query 5
Query 6
Query 7
Query 8
DB2 And SQL
DB2 Concept DB2 Data Structures ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Structure Storage Group: STG1 (STOGROUP) DATABASE  DB1 INDEX A INDEX C Storage Group:  STG2 TABLE A TABLE B Tablespace: TS1 TABLE C Tablespace: TS2
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.
DB2 Concept  The Hierarchy of DB2 Structures  Database D1 Table T1 Table T2 Table space S1 Index X1 Index X2 Table T3 Part 1 Table T3 Part 2 Partitioned Table space S2 Partitioned index X3 Part 2 Partitioned index X3 Part 2 Storage Group G1 3390 Storage Group  G2 3380
DB2 Concept  The Hierarchy of DB2 Structures  Storage Group Database Table Space Table Column Index View Alias Synonym
DB2 Concept Database/Storage Groups Database ,[object Object],[object Object],[object Object],[object Object],[object Object],Storage Groups ,[object Object],[object Object],[object Object]
DB2 Concept Table Spaces Table Spaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Concept  Simple Table Spaces Simple Table Spaces page page page page page page ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Table Space
DB2 Concept  Segmented Table Spaces Table A Table B Table C Segmented Table Spaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Table Space page Segment 3 page Segment 2 Segment 1 page
DB2 Concept  Partitioned Table Spaces Partitioned Table Spaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Key  range A~H Key  range I~Q Key  range R~Z Table Space page Partition 3 page Partition 2 Partition 1 page
DB2 Concept Table/Index  Table  ,[object Object],[object Object],[object Object],Index  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Concept  Views  Views  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],User 1 Table 1 Table 2 Table 3 Table 4 View 1 View 2 View 3 User 2
Physical Design Issue Designing Tables and View ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],DB2 Concept Physical Design Issue
DB2 Concept Physical Design Issue Physical Design Issue Designing Columns ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Concept Physical Design Issue Physical Design Issue Designing 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 &quot;page&quot; size. DESCRIPTION fixed length string variable length string (or longer than 254 char) LENGTH x characters (maximum 254) 0 to x characters (maximum 4K*)
DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Double byte Data Type DATA TYPE GRAPHIC(x) VARGRAPHIC(x) * Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as &quot;page&quot; size. DESCRIPTION fixed length  string variable length string (or longer than 127 char) LENGTH x characters (maximum 128) 0 to x characters (maximum 2K*)
DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Numeric Data Type DATA TYPE SMALLINT INTEGER INT DECIMAL(x,y) DEC(x,y) NUMERIC(x,y) FLOAT(m) REAL FLOAT FLOAT(n) DOUBLE PRECISION * Approximately  **1 <= m <= 21,  22 <= n <= 53 DESCRIPTION Whole numbers Whole numbers x digits, of which y are to the right of the decimal point short floating point ** log floating point ** RANGE    32K*    2 Billion up to 32 digits 5.4E-79 to 7.2E+75 5.4E-79 to 7.2E+75
DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Date, Time, Timestamp Data Type DATA TYPE DATE TIME TIMESTAMP INTERNAL FORMAT yyyymmdd hhmmss yyyymmddhhmmssnnnnnn (nnnnnn = microseconds)
DB2 Concept Physical Design Issue Physical Design Issue Designing Columns ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Concept Physical Design Issue Physical Design Issue Designing Index ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DB2 Concept Physical Design Issue Physical Design Issue ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Data Integrity -  Terminology
DB2 Concept Physical Design Issue DEPTNO ... C01 DEPTNAME ....... INFORMATION CENTER PRIMARY KEY OPERATIONS ... ... ... ... ... ... E11 DEPARTMENT table FOREIGN KEY EMPNO 000030 000090 000130 000290 000300 .... FIRSTNM SALLY EILEEN DOLORES JOHN PHILIP .... LASTNAM KWAN HENDERSON QUINTANA PARKER SMITH .... ... ... ... ... ... ... ... DEPT C01 E11 C01 E11 E11 ... ... ... ... ... ... ... ... PRIMARY KEY EMPLOYEE table
DB2 Concept -- Referential Integrity ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Referential Integrity
DB2 Concept -- Referential Integrity 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 and Structured Query Language
SQL Summary SQL Data Definition Language  (DDL) Data Manipulation Language (DML) Data Control Language (DCL) CREATE DROP ALTER SELECT INSERT UPDATE DELETE GRANT REVOKE
DB2 Programming Concept SQL  语言特性 : . 取代传统的 DO PROCEDURE LANGUAGE . 程序设计者 只需 申明 需要 哪些资料 ,不需 申明 如何取得 这些资料 . 不仅是数据查询 工具 ,也能进行数据管理 . 命令语法易学易懂 - SELECT * FROM DA. TBDAMF WHERE APPLID = 'DA'; - UPDATE DA.TBDAMF SET  FILE = 'AAAAAA' WHERE EMPNO = '111111';
DB2  and  Data Definition Language
Data Definition Language (DDL) ALTER  statement :  ALTER STOGROUP ALTER TABLESPACE,  ALTER TABLE,  ALTER INDEX 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
Data Definition Language (DDL) -- CREATE CREATE STOGROUP  stogroup-name   VOLUMES  volume-id   VCAT  catalog-name   PASSWORD  password ; CREATE STOGROUP  IBMST001   VOLUMES  ACA301  VCAT  DSNCAT PASSWORD  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
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
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
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.
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.
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
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
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, ….);
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
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 NULL RESTRICT  -- if there are tuples in the referenced table, cause an  error to occur CASCADE  -- 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
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. ***  NOTE :  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;
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  ) ….
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
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-name CLUSTER; 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.
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)
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.
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.IBMNX001 ON IBMDB001.TAB001 ( PROJECT-NO ASC) USING STOGROUP IBMSG001 CLUSTER;
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  subselect WITH [ CASCADED  |  LOCAL ] CHECK OPTION; Privilege Needed:  SELECT  (on each table or view)  or Ownership of the table  or DBADM   or  SYSADM  or  SYSCTRL
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, EMPLOYEE WHERE EMP-NO = ‘12349’; Page:2-35 Data Definition Language (DDL) --  CREATE VIEW
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
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
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,...); error occurs and no rows are inserted Data Definition Language (DDL) --  CREATE VIEW
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)
SYSIBM.SYSTABLES SYSIBM.SYSCOLUMNS SYSIBM.SYSVIEWS SYSIBM.SYSVIEWDP Since views are virtual tables, Db2 will keep information about them 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 (DDL) --  CREATE VIEW ( View Catalog Information)
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],(DDL) --  CREATE VIEW ( Good Reasons to use views)
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  or DBCTRL  or  SYSADM  or  SYSCTRL To drop a synonym:  Ownership
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 ;
DB2 and Data Control Language
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.
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 Data Control Language (DCL)-- GRANT
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 IBMDB001 TO PUBLIC ; Data Control Language (DCL)-- GRANT
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 IBMDB001 TO T90XXX, T90YYY, T90ZZZ, …. ; Data Control Language (DCL)-- GRANT
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
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
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;   Data Control Language (DCL)
DB2 And  DML
INSERT statement Inserts 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 Data Manipulation Language (DML)
INSERT INTO  [  table-name  |  view-name  ]  VALUES (.., .., .., .., ..); INSERT INTO [  table-name  |  view-name  ]  ( column-name , …, …, ) VALUES (.., .., .., .., ..); INSERT INTO [  table-name  |  view-name  ] subselec t ; INSERT INTO [  table-name  |  view-name  ]  ( column-name , …, …, ) subselect ; Data Manipulation Language (DML) --  INSERT
INSERT INTO  TAB001 VALUES ( ‘00024’ ,  ‘Mary’ ,  ‘D11’ ,  15 ); INSERT INTO  TAB002 ( CUSTOMER-ID, CUSTOMER-NAME,  CUSTOMER-ROOM-NUMBER, CUSTOMER-AGE )  VALUES ( ‘00024’, ‘Mary’, ‘D11’, 15 ); INSERT INTO  VIEW001 SELECT *   FROM TAB003 ; INSERT INTO  VIEW002 SELECT *   FROM TAB003   WHERE GPA > 3.0; 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. Data Manipulation Language (DML) --  INSERT
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 Data Manipulation Language (DML)
Searched update: UPDATE [  table-name  |  view-name  ] SET  column-name  = [  expressio n  | 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 ; Data Manipulation Language (DML) --  UPDATE
UPDATE  TAB001 SET  PHONE-NUMBER  =  ‘815-753-6945’ WHERE  EMPLOYEE_NUMBER = ‘E293’ ; UPDATE  TAB001 SET  SALARY = SALARY + 100 WHERE  EMPLOYEE_NUMBER = ‘E948’ ; Embedded in COBOL: EXEC SQL UPDATE  TAB003 SET  SALARY = 2 * SALARY WHERE CURRENT OF  CURSOR1 ; END-EXEC. 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 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. Data Manipulation Language (DML) --  UPDATE
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 Data Manipulation Language (DML)
Searched delete: DELETE FROM  [  table-name  |  view-name  ] WHERE  search-condition ; Positioned delete: DELETE FROM [  table-name  |  view-name  ] WHERE CURRENT OF  cursor-name ; Data Manipulation Language (DML) --  DELETE
DELETE FROM  TAB001 WHERE  DEPT-NUMBER = ‘E11’   OR  DEPT-NUMBER = ‘D21’ ; Embedded in COBOL program: EXEC SQL DELETE FROM  TAB003 WHERE CURRENT OF  CURSOR1 ;   END-EXEC. Data Manipulation Language (DML) --  DELETE
SQL Statement Performance-access path Access Paths   Typical access paths: Table(space) scan Matching index scan No-matching index scan Index-only access The Access Path is determined by the Optimizer in DB2. It can be influenced by the way you write your SQL statement.
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%’
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’
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) S mith,Stanley(8,2) S mith,Steve(8,1) Thompson,Tom(6,3) Zidler,Bob(6,1) Jones,Bob Reeves,Susan Peters,Joan Adams,Mark Mitchell,David Bennett,Barb Davis,Mac Howell,Thurston . Jefferson,Tom Lee,Spike . Champman,Mike Adams,Mark . Zidler,Bob Quinn,Tonny Thompson,Tom Lincoln, Abe Alvani,Cart . S mith,Steve S mith,Stanley . Data Pages Root Page Leaf Pages
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
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
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
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
INDEXED Column is... DB2's USE OF INDEXES Used with: IN LIKE BETWEEN >,>=,<,<=,  >,  <,=  =,<> NOT OR ORDER BY GROUP BY DISTINCT^ Compared to: longer literal arithmetic exp. diff. data type Used for JOIN INDEX Candidate YES NOTE1 YES YES NO NOTE2 NOTE3 YES YES YES NO NO NO YES Sort Candidate YES YES YES YES NOTE1 : YES, except when string is host-variable, or string is of the form '%...' or '-...' NOTE2 : Apply NOT, then evaluate NOTE3 : NO unless convertible to in DB2 -- SQL Statement Performance
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
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
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
BATCH  TSO  and DB2  EMBEDDED SQL
DB2 Programming Concept  SAMPLE PROGRAM  REVIEW  SAMPLE PROGRAM  REVIEW  ,[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],Batch TSO
//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
Source Program Precompiler DCLGEN DBRM Modified Source Compiler Compiled Source Linkage Editor Load Module Bind Package Package Bind Plan Plan DB2 Catalog DB2 Directory DB2 Embedded SQL -- Program Preparation
DB2 PROGRAM  PREPARATION ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],声明 TABLE 结构 DB2 Embedded SQL -- Program Preparation
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. DVLP.BOOKLIB(EMPXXRCD) Embedded SQL -- DCLGEN
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. To Use  DCLGEN , select option 2 from the DB2I Primary Option Menu.  EMP99 EDUCS99 ‘ DVLP.BOOKLIB(EMP99RCD)’ EMP99DCL Embedded SQL -- DCLGEN
Option 1 : SOURCE TABLE NAME The 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. EMP99 DVLP Embedded SQL -- DCLGEN
Option 4:  DATA SET NAME Here 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 PASSWORD If the data set has a password, specify it here. ‘ DVLP.BOOLIB(EMP99RCD)’ Embedded SQL -- DCLGEN
Option 6 :  ACTION Specifies 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
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. Option 8 :  STRUCTURE NAME Uses 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 Embedded SQL -- DCLGEN
Option 9 :  FIELD NAME PREFIX Specifies 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. EMP99DCL Embedded SQL -- DCLGEN
The PRECOMPILE- Functions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],DB2 Embedded SQL -- Program Preparation
SQL INCLUDE  Statement   ,[object Object],[object Object],[object Object],[object Object],Cobol program code: EXEC SQL INCLUDE EMP99RCD END EXEC. PAGE:3-24
SQL Communication Area - SQLCA  SQL Stmt SQLCA Program  checks returned  values Execute  SQL stmt and Updates the  Comm Area Program  DB2 SQLCODE
SQL INCLUDE  SQLCA Statement  Used to Include SQLCA declaration ,[object Object],[object Object],[object Object],[object Object],The precompiler  generate  an  SQLCA in your program
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). Embedded SQL -- SQLCA
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. DB2 Embedded SQL -- Program Preparation
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],DVLP.DBRM Program Preparation-Precompile
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
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. Program Preparation-Precompile
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Program Preparation-Precompile
[object Object],[object Object],[object Object],[object Object],[object Object],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.  Compilation and LINK-EDIT
BIND PACKAGE runs in TSO(Online or Batch) BIND PACKAGE  creates a package in the DB2 directory ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Page:3-38 BIND PACKAGE
Package: 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   DB2 Embedded SQL -- Program Preparation
DBRM BIND PACKE(collx) MEMBER(dbrma) BIND PACKE(colly) MEMBER(dbrma) colly dbrma dbrmb Dbrm... Package name= collection_id.package_id PACKAGE collx dbrma dbrmb Dbrm...
A collection is a set of packages. A package is bound in a collecion. A collection is implicitly created at first BIND PACKAGE referring to that collection. Example: BIND PACKAGE( online ) MEMBER(pkg1) BIND PACKAGE( batch )  MEMBER(pkg3) Collection(packageset) online pkg1 pkg2 batch pkg3 pkg4
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) Collection(packageset) test_payroll pkg1 pkg2 prod_payroll pkg1 pkg3
Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,   ,2) ... Mprog1 ... call DSNHLI ( dbrm2 ,   ,1) ... Call     Call   call   DB2 Directory colly dbrm1   ? Page:3-44 Locating PACKAGEs at execution time collx dbrm1   dbrm3  collz dbrm2   dbrm4 
Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,   ,2) ... Mprog2 ... call DSNHLI ( dbrm2 ,   ,1) ... Call     Call   call   DB2 Directory colly dbrm1   Page:3-44 Collx.dbrm1,collz.* plana BIND PLAN(plana) Pklist(Collx.dbrm1,collz.*) Locating PACKAGEs at execution time collx dbrm1   dbrm3  collz dbrm2   dbrm4 
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. Locating PACKAGEs at execution time
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 PLAN A 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 ) PLAN and  PACKAGEs
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.SYSTABLES SYSIBM.SYSTABLESPACE  SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH Information about plans is then stored in the following tables: SYSIBM.SYSDBRM SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKLIST SYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSPLANDEP SYSIBM.SYSPLSYSTEM SYSIBM.SYSSTMT SYSIBM.SYSTABAUTH PLAN and  PACKAGEs
BIND PLAN(plana)  PKLIST(Collx.dbrm1,collz.*) BIND PLAN(plana)  PKLIST(Collx.dbrm1,collz.*) MEMBER(dbrma,dbrm1) BIND PLAN(plana)  MEMBER(dbrma,dbrm1) collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2   Instream DBRM BIND PLAN - DBRMS
collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,   ,1) ... Instream DBRM first! PACKAGE Search
collx.dbrm1,colly.* plana collx.dbrm1,colly.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,   ,1) ... Sqlcode: -818 Sqlcode: -805 colly dbrm1  Timestamp Mismatch Errors
TSO  RUN PROGRAM( mprog1 )   PLAN( plana ) CICS  RCT(Resource Control Table) IMS  RTT(Resource Translate Table) CAF  Callable Interface(DSNALI) RRSAF  DSNRLI Running the Program
Each execution environment has its own language interface LINK-EDIT
... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE QUAL(TEST) BIND PACKAGE QUAL(PROD) BIND PACKAGE TEST .TAB1  binder .TAB1  PROD .TAB1 binder BIND PACKAGE OR PLAN BIND - QUALIFIER Option
... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE(usdcol) QUAL(usd) USD .TAB1   YEN .TAB1 dbrm1  usdcol BIND PACKAGE(yencol) QUAL(yen) dbrm1  yencol Same structure TABLE Mirroring-1
...  SELECT ... FROM TAB1 ...   USD .TAB1   YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-2
coll =  ‘yencol’ . SET CURRENT PACKAGESET=:coll . SELECT ... FROM TAB1   USD .TAB1   YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-3
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 Special Register- CURRENT PACKAGESET
pgma   UTTEST.SRC Precompile version (uttest) Precompile version (systest) pgma   UTTEST.LOAD pgma   SYSTEST.LOAD BIND PACKAGE(collx) MEMBER(pgma) pgma   collx pgma   pgma   UTTEST.SRC PACKAGE VERSIONING
RR  (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  COMMIT S or  ROLLBACK S.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. 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 ). 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. 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. 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. Data Consistency-Isolation Level
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. DB2 Embedded SQL -- Program Preparation
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 FREE / DROP
Source Program DCLGEN Precompiler DBRM Bind Package Package Plan DB2 Catalog DB2 Directory Modified Source(SQL) Compiler Compiled Source Linkage Editor Load Module CICS TRANSLATE Modified Source EXEC SQL  转换成  CALL  语句 EXEC CICS 转换成 CALL 语句 Plan Package Package Package Package Package Package ,[object Object],[object Object],translate ispf editer dclgen Program Preparation-Summary  Version level
DB2 AND COBOL DB2 & COBOL
DB2 Programming Concept    DB2  Ap p l i c a t i o n  S t r u c t u r e DB2  Ap p l i c a t i o n  S t r u c t u r e ․  WORKING STORAGE SECTION - INCLUDE TABLE STRUCTURE - INCLUDE SQLCA - CURSOR DECLARATION ․  PROCEDURE DIVISION - ERROR HANDLING - DML SQL STATEMENT - CURSOR HANDLING - CHECK SQLCODE
Two types or embedded SQL statements: 1.  Singleton SELECTs -- MUST select  only ONE row.  And MUST contain  INTO clause. Here the names of the host variables that will accept the  data returned by DB2 are listed. 2.  Cursor SELECTs -- Processes multiple  rows. Embedded SQL
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Embedded SQL-  SQL Coding Rules
[object Object],[object Object],EXEC SQL INCLUDE CUST  END-EXEC. EXEC SQL INCLUDE SQLCA END-EXEC. Embedded SQL-  SQL Coding Rules
What you DON’T code for a DB2 Table: 1.  A COBOL SELECT statement 2.  A File Description entry 3.  A Record Description What you DO or CAN code: 1.  INCLUDE statement for SQL Communications Area 2.  Table Declarations 3.  Host Variables 4.  Cursors Embedded SQL
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],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). Embedded SQL -- SQLCA
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Embedded SQL -- SQLCA
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Embedded SQL -- SQLCA
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
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
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.  DATE 2.  SMALLINT   6.  TIME 3.  INTEGER 7.  TIMESTAMP 4.  DECIMAL Embedded SQL -- Host Structures
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
When using host variables in SQL statements, you must precede the host variable name with a colon( : ). Example: EXEC SQL SELECT  FNAME,  LNAME,  ADDRESS INTO :FNAME,  :LNAME,  :ADDR FROM  PERSON WHERE 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
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
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
Processing Multiple Rows EMPNO LASTNAME 000030 000290 000300 KWAN PARKER SMITH .  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 until break Embedded SQL -- Cursors
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
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
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 a DECLARE 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
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 SQL OPEN INSTCURS END-EXEC. OPEN  is coded in the  PROCEDURE DIVISION . Embedded SQL -- Cursors
Closing a Cursor CLOSE  statement releases the results table associated with the specified cursor.  EXEC SQL CLOSE  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
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 SQL FETCH INSTCURS INTO :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
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
EXEC SQL DECLARE  CX  CURSOR FOR SELECT EMPNO, LASTNAME FROM EMP99 WHERE DEPTNO = :DPT FOR UPDATE OF LASTNAME END-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
- 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
COMMIT - CURSOR REPOSITIONING EXEC 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
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],UR + FOR UPDATE OF = CS Cursors-- Read-Only  CURSORS
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. Cursors-- Optimize for n Rows
EXEC SQL DECLARE C1 CURSOR FOR SELECT .  .  .  WITH RR/RS/CS/UR  END-EXEC. ,[object Object],[object Object],[object Object],Cursors-- with RR/RS/CS/UR
EXEC SQL DECLARE C1 CURSOR FOR SELECT .  .  .  WITH RR/RS KEEP UPDATE LOCKS  END-EXEC. ,[object Object],[object Object],[object Object],Cursors-- keep update locks
SELECT statement In PROCEDURE DIVISION: EXEC SQL SELECT   column-specification,  [ column-specification, … ] INTO   : host-var,  [: host-var… ]   : host-structure FROM   table-name,  [ table-name,… ] [  WHERE   selection-condition  ] END-SQL. Embedded SQL -- Select
column-specification A description of what the  SELECT  statement should put in the  corresponding results table EXEC SQL SELECT   column-specification,  [ column-specification, … ] Embedded SQL -- Select
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
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
Example: Say you have the following FNAME data in the person table: BOB  GREEN MARY WHITE JANE  SMITH To return the first and last name of a person with the first name “BOB”, you execute the statement: EXEC SQL SELECT LNAME, FNAME INTO :LNAME, FNAME FROM PERSON WHERE  FNAME = ‘BOB’  END-EXEC. When this SQL statement executes, it returns a one row results table: BOB GREEN Embedded SQL -- Select
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 SQL FETCH NAMEINFO INTO :FNAME,  :LNAME  END-EXEC. Embedded SQL -- Select
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
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 USER Extracts the current user id from the DB2 catalog and adds it to the results table. Embedded SQL -- Select
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  -  :TAX Character 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
FROM clause The  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 clause The  INTO  clause of the  SELECT  statement names the  COBOL host variables into which DB2 will place the  results table data. SELECT  FNAME, LNAME INTO  :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
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
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2
Db2

More Related Content

What's hot

DB2 Interview Questions - Part 1
DB2 Interview Questions - Part 1DB2 Interview Questions - Part 1
DB2 Interview Questions - Part 1ReKruiTIn.com
 
Solving the DB2 LUW Administration Dilemma
Solving the DB2 LUW Administration DilemmaSolving the DB2 LUW Administration Dilemma
Solving the DB2 LUW Administration DilemmaRandy Goering
 
Understanding DB2 Optimizer
Understanding DB2 OptimizerUnderstanding DB2 Optimizer
Understanding DB2 Optimizerterraborealis
 
DB2 and storage management
DB2 and storage managementDB2 and storage management
DB2 and storage managementCraig Mullins
 
Introduction of ISPF
Introduction of ISPFIntroduction of ISPF
Introduction of ISPFAnil Bharti
 
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the myths
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the mythsDB2 for z/OS and DASD-based Disaster Recovery - Blowing away the myths
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the mythsFlorence Dubois
 
JCL UTILITIES IEBCOPY
JCL UTILITIES IEBCOPYJCL UTILITIES IEBCOPY
JCL UTILITIES IEBCOPYjanaki ram
 
DB2 LUW - Backup and Recovery
DB2 LUW - Backup and RecoveryDB2 LUW - Backup and Recovery
DB2 LUW - Backup and Recoveryimranasayed
 
Oracle dba training
Oracle  dba    training Oracle  dba    training
Oracle dba training P S Rani
 
A First Look at the DB2 10 DSNZPARM Changes
A First Look at the DB2 10 DSNZPARM ChangesA First Look at the DB2 10 DSNZPARM Changes
A First Look at the DB2 10 DSNZPARM ChangesWillie Favero
 
JCL MAINFRAMES
JCL MAINFRAMESJCL MAINFRAMES
JCL MAINFRAMESkamaljune
 
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OS
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OSPractical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OS
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OSCuneyt Goksu
 
IBM DB2 LUW UDB DBA Training by www.etraining.guru
IBM DB2 LUW UDB DBA Training by www.etraining.guruIBM DB2 LUW UDB DBA Training by www.etraining.guru
IBM DB2 LUW UDB DBA Training by www.etraining.guruRavikumar Nandigam
 
Oracle architecture with details-yogiji creations
Oracle architecture with details-yogiji creationsOracle architecture with details-yogiji creations
Oracle architecture with details-yogiji creationsYogiji Creations
 
DB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and OptimisationDB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and OptimisationJohn Campbell
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overviewhonglee71
 

What's hot (20)

DB2 Interview Questions - Part 1
DB2 Interview Questions - Part 1DB2 Interview Questions - Part 1
DB2 Interview Questions - Part 1
 
Solving the DB2 LUW Administration Dilemma
Solving the DB2 LUW Administration DilemmaSolving the DB2 LUW Administration Dilemma
Solving the DB2 LUW Administration Dilemma
 
Understanding DB2 Optimizer
Understanding DB2 OptimizerUnderstanding DB2 Optimizer
Understanding DB2 Optimizer
 
IBM DB2
IBM DB2IBM DB2
IBM DB2
 
DB2 and storage management
DB2 and storage managementDB2 and storage management
DB2 and storage management
 
Introduction of ISPF
Introduction of ISPFIntroduction of ISPF
Introduction of ISPF
 
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the myths
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the mythsDB2 for z/OS and DASD-based Disaster Recovery - Blowing away the myths
DB2 for z/OS and DASD-based Disaster Recovery - Blowing away the myths
 
JCL UTILITIES IEBCOPY
JCL UTILITIES IEBCOPYJCL UTILITIES IEBCOPY
JCL UTILITIES IEBCOPY
 
DB2 LUW - Backup and Recovery
DB2 LUW - Backup and RecoveryDB2 LUW - Backup and Recovery
DB2 LUW - Backup and Recovery
 
Oracle dba training
Oracle  dba    training Oracle  dba    training
Oracle dba training
 
Jcl
JclJcl
Jcl
 
DB2 on Mainframe
DB2 on MainframeDB2 on Mainframe
DB2 on Mainframe
 
A First Look at the DB2 10 DSNZPARM Changes
A First Look at the DB2 10 DSNZPARM ChangesA First Look at the DB2 10 DSNZPARM Changes
A First Look at the DB2 10 DSNZPARM Changes
 
JCL MAINFRAMES
JCL MAINFRAMESJCL MAINFRAMES
JCL MAINFRAMES
 
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OS
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OSPractical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OS
Practical Recipes for Daily DBA Activities using DB2 9 and 10 for z/OS
 
IBM DB2 LUW UDB DBA Training by www.etraining.guru
IBM DB2 LUW UDB DBA Training by www.etraining.guruIBM DB2 LUW UDB DBA Training by www.etraining.guru
IBM DB2 LUW UDB DBA Training by www.etraining.guru
 
Oracle architecture with details-yogiji creations
Oracle architecture with details-yogiji creationsOracle architecture with details-yogiji creations
Oracle architecture with details-yogiji creations
 
DB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and OptimisationDB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
DB2 10 & 11 for z/OS System Performance Monitoring and Optimisation
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
Mainframe interview
Mainframe interviewMainframe interview
Mainframe interview
 

Viewers also liked

Planning and executing a DB2 11 for z/OS Migration by Ian Cook
Planning and executing a DB2 11 for z/OS  Migration  by Ian Cook Planning and executing a DB2 11 for z/OS  Migration  by Ian Cook
Planning and executing a DB2 11 for z/OS Migration by Ian Cook Surekha Parekh
 
DB2 Accounting Reporting
DB2  Accounting ReportingDB2  Accounting Reporting
DB2 Accounting ReportingJohn Campbell
 
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...InSync2011
 
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...InSync2011
 
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...InSync2011
 
MongoDB: Prós, Contras e Showcases.
MongoDB: Prós, Contras e Showcases.MongoDB: Prós, Contras e Showcases.
MongoDB: Prós, Contras e Showcases.Leonardo Quevedo
 
Using Release(deallocate) and Painful Lessons to be learned on DB2 locking
Using Release(deallocate) and Painful Lessons to be learned on DB2 lockingUsing Release(deallocate) and Painful Lessons to be learned on DB2 locking
Using Release(deallocate) and Painful Lessons to be learned on DB2 lockingJohn Campbell
 
MAGICDB : Mango Genetic stocks Identification and Characterisation Data Base
MAGICDB : Mango Genetic stocks Identification and Characterisation Data BaseMAGICDB : Mango Genetic stocks Identification and Characterisation Data Base
MAGICDB : Mango Genetic stocks Identification and Characterisation Data BaseSenthil Natesan
 
Curs integral-neurologie-sem-1-i-ii
Curs integral-neurologie-sem-1-i-iiCurs integral-neurologie-sem-1-i-ii
Curs integral-neurologie-sem-1-i-iiAlexandra Ally
 
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - faveroWillie Favero
 
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...John Campbell
 
Oracle Database Introduction
Oracle Database IntroductionOracle Database Introduction
Oracle Database IntroductionChhom Karath
 
DB2 for z/OS - Starter's guide to memory monitoring and control
DB2 for z/OS - Starter's guide to memory monitoring and controlDB2 for z/OS - Starter's guide to memory monitoring and control
DB2 for z/OS - Starter's guide to memory monitoring and controlFlorence Dubois
 
Parallel Sysplex Implement2
Parallel Sysplex Implement2Parallel Sysplex Implement2
Parallel Sysplex Implement2ggddggddggdd
 
FlashCopy and DB2 for z/OS
FlashCopy and DB2 for z/OSFlashCopy and DB2 for z/OS
FlashCopy and DB2 for z/OSFlorence Dubois
 

Viewers also liked (19)

Planning and executing a DB2 11 for z/OS Migration by Ian Cook
Planning and executing a DB2 11 for z/OS  Migration  by Ian Cook Planning and executing a DB2 11 for z/OS  Migration  by Ian Cook
Planning and executing a DB2 11 for z/OS Migration by Ian Cook
 
DB2 Accounting Reporting
DB2  Accounting ReportingDB2  Accounting Reporting
DB2 Accounting Reporting
 
Db2
Db2Db2
Db2
 
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...
Databse & Technology 2 | Connor McDonald | Managing Optimiser Statistics - A ...
 
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...
Databse & Technology 2 _ Francisco Munoz alvarez _ 11g new functionalities fo...
 
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...
Databse & Technology 2 _ Paul Guerin _ The biggest looser database - a boot c...
 
MongoDB: Prós, Contras e Showcases.
MongoDB: Prós, Contras e Showcases.MongoDB: Prós, Contras e Showcases.
MongoDB: Prós, Contras e Showcases.
 
Zodb
ZodbZodb
Zodb
 
Firebird
FirebirdFirebird
Firebird
 
Using Release(deallocate) and Painful Lessons to be learned on DB2 locking
Using Release(deallocate) and Painful Lessons to be learned on DB2 lockingUsing Release(deallocate) and Painful Lessons to be learned on DB2 locking
Using Release(deallocate) and Painful Lessons to be learned on DB2 locking
 
MAGICDB : Mango Genetic stocks Identification and Characterisation Data Base
MAGICDB : Mango Genetic stocks Identification and Characterisation Data BaseMAGICDB : Mango Genetic stocks Identification and Characterisation Data Base
MAGICDB : Mango Genetic stocks Identification and Characterisation Data Base
 
DB2 9.7 Overview
DB2 9.7 OverviewDB2 9.7 Overview
DB2 9.7 Overview
 
Curs integral-neurologie-sem-1-i-ii
Curs integral-neurologie-sem-1-i-iiCurs integral-neurologie-sem-1-i-ii
Curs integral-neurologie-sem-1-i-ii
 
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...
DB2 for z/OS Bufferpool Tuning win by Divide and Conquer or Lose by Multiply ...
 
Oracle Database Introduction
Oracle Database IntroductionOracle Database Introduction
Oracle Database Introduction
 
DB2 for z/OS - Starter's guide to memory monitoring and control
DB2 for z/OS - Starter's guide to memory monitoring and controlDB2 for z/OS - Starter's guide to memory monitoring and control
DB2 for z/OS - Starter's guide to memory monitoring and control
 
Parallel Sysplex Implement2
Parallel Sysplex Implement2Parallel Sysplex Implement2
Parallel Sysplex Implement2
 
FlashCopy and DB2 for z/OS
FlashCopy and DB2 for z/OSFlashCopy and DB2 for z/OS
FlashCopy and DB2 for z/OS
 

Similar to Db2

Complete reference to_abap_basics
Complete reference to_abap_basicsComplete reference to_abap_basics
Complete reference to_abap_basicsAbhishek Dixit
 
Track 2 session 4 db2 for z os optimizer- what’s new in db2 11 and exploiti...
Track 2 session 4   db2 for z os optimizer- what’s new in db2 11 and exploiti...Track 2 session 4   db2 for z os optimizer- what’s new in db2 11 and exploiti...
Track 2 session 4 db2 for z os optimizer- what’s new in db2 11 and exploiti...IBMSystemzEvents
 
Lsmw by guntupalliharikrishna
Lsmw by guntupalliharikrishnaLsmw by guntupalliharikrishna
Lsmw by guntupalliharikrishnaHari Krishna
 
Top Ten Siemens S7 Tips and Tricks
Top Ten Siemens S7 Tips and TricksTop Ten Siemens S7 Tips and Tricks
Top Ten Siemens S7 Tips and TricksDMC, Inc.
 
First fare 2010 lab-view creating custom dashboards
First fare 2010 lab-view creating custom dashboardsFirst fare 2010 lab-view creating custom dashboards
First fare 2010 lab-view creating custom dashboardsOregon FIRST Robotics
 
DB2 UDB for z/OS Version 7 - An Overview
DB2 UDB for z/OS Version 7 - An OverviewDB2 UDB for z/OS Version 7 - An Overview
DB2 UDB for z/OS Version 7 - An OverviewCraig Mullins
 
Exclusive SAP Basis Training Book | www.sapdocs.info
Exclusive SAP Basis Training Book | www.sapdocs.infoExclusive SAP Basis Training Book | www.sapdocs.info
Exclusive SAP Basis Training Book | www.sapdocs.infosapdocs. info
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxketurahhazelhurst
 
Sap basis made_easy321761331053730
Sap basis made_easy321761331053730Sap basis made_easy321761331053730
Sap basis made_easy321761331053730K Hari Shankar
 
Build a Big Data solution using DB2 for z/OS
Build a Big Data solution using DB2 for z/OSBuild a Big Data solution using DB2 for z/OS
Build a Big Data solution using DB2 for z/OSJane Man
 
Lsmw for master data upload simple explanation
Lsmw for master data upload simple explanationLsmw for master data upload simple explanation
Lsmw for master data upload simple explanationManoj Kumar
 
Scm lsmw steps_onweb
Scm lsmw steps_onwebScm lsmw steps_onweb
Scm lsmw steps_onwebHarsha Reddy
 
zOSMF Desktop UI Hands-On Lab.pdf
zOSMF Desktop UI Hands-On Lab.pdfzOSMF Desktop UI Hands-On Lab.pdf
zOSMF Desktop UI Hands-On Lab.pdfMarna Walle
 
Change transport system in SAP
Change transport system in SAP Change transport system in SAP
Change transport system in SAP chinu141
 
LSMW-STEP-BY-STEP-RECORD.pdf
LSMW-STEP-BY-STEP-RECORD.pdfLSMW-STEP-BY-STEP-RECORD.pdf
LSMW-STEP-BY-STEP-RECORD.pdfKaveriBangar1
 
Chapter9 and10
Chapter9 and10Chapter9 and10
Chapter9 and10Saurav
 
Chapter9and10
Chapter9and10Chapter9and10
Chapter9and10Saurav
 
Uploading customer master extended address using bapi method
Uploading customer master extended address using bapi methodUploading customer master extended address using bapi method
Uploading customer master extended address using bapi methodlondonchris1970
 

Similar to Db2 (20)

Complete reference to_abap_basics
Complete reference to_abap_basicsComplete reference to_abap_basics
Complete reference to_abap_basics
 
Track 2 session 4 db2 for z os optimizer- what’s new in db2 11 and exploiti...
Track 2 session 4   db2 for z os optimizer- what’s new in db2 11 and exploiti...Track 2 session 4   db2 for z os optimizer- what’s new in db2 11 and exploiti...
Track 2 session 4 db2 for z os optimizer- what’s new in db2 11 and exploiti...
 
Lsmw by guntupalliharikrishna
Lsmw by guntupalliharikrishnaLsmw by guntupalliharikrishna
Lsmw by guntupalliharikrishna
 
Top Ten Siemens S7 Tips and Tricks
Top Ten Siemens S7 Tips and TricksTop Ten Siemens S7 Tips and Tricks
Top Ten Siemens S7 Tips and Tricks
 
First fare 2010 lab-view creating custom dashboards
First fare 2010 lab-view creating custom dashboardsFirst fare 2010 lab-view creating custom dashboards
First fare 2010 lab-view creating custom dashboards
 
DB2 UDB for z/OS Version 7 - An Overview
DB2 UDB for z/OS Version 7 - An OverviewDB2 UDB for z/OS Version 7 - An Overview
DB2 UDB for z/OS Version 7 - An Overview
 
Exclusive SAP Basis Training Book | www.sapdocs.info
Exclusive SAP Basis Training Book | www.sapdocs.infoExclusive SAP Basis Training Book | www.sapdocs.info
Exclusive SAP Basis Training Book | www.sapdocs.info
 
Tso and ispf
Tso and ispfTso and ispf
Tso and ispf
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
 
Sap basis made_easy321761331053730
Sap basis made_easy321761331053730Sap basis made_easy321761331053730
Sap basis made_easy321761331053730
 
Build a Big Data solution using DB2 for z/OS
Build a Big Data solution using DB2 for z/OSBuild a Big Data solution using DB2 for z/OS
Build a Big Data solution using DB2 for z/OS
 
Lsmw for master data upload simple explanation
Lsmw for master data upload simple explanationLsmw for master data upload simple explanation
Lsmw for master data upload simple explanation
 
Scm lsmw steps_onweb
Scm lsmw steps_onwebScm lsmw steps_onweb
Scm lsmw steps_onweb
 
zOSMF Desktop UI Hands-On Lab.pdf
zOSMF Desktop UI Hands-On Lab.pdfzOSMF Desktop UI Hands-On Lab.pdf
zOSMF Desktop UI Hands-On Lab.pdf
 
Change transport system in SAP
Change transport system in SAP Change transport system in SAP
Change transport system in SAP
 
LSMW-STEP-BY-STEP-RECORD.pdf
LSMW-STEP-BY-STEP-RECORD.pdfLSMW-STEP-BY-STEP-RECORD.pdf
LSMW-STEP-BY-STEP-RECORD.pdf
 
Chapter9 and10
Chapter9 and10Chapter9 and10
Chapter9 and10
 
Chapter9and10
Chapter9and10Chapter9and10
Chapter9and10
 
Uploading customer master extended address using bapi method
Uploading customer master extended address using bapi methodUploading customer master extended address using bapi method
Uploading customer master extended address using bapi method
 
Bdc
BdcBdc
Bdc
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Db2

  • 1. DB2 UDB for z/OS Application Programming Workshop Wu Chi 027- 87544884 [email_address]
  • 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.
  • 3. DB2 Slides -- Index Topic 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
  • 6.  
  • 7.
  • 8. End-User’s View They See tables & issue SQL DML statements Don’t see other programs; Don’t worry about data integrity, and so on
  • 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
  • 10. DML language SELECT * FORM EMP WHERE EMPNO=‘000010’ UPDATE INSERT DELETE
  • 11. Static end users Use specific programs(transactions) to perform specific actions on DB2 data. Need not knonw SQL, DB2
  • 12. The Static Program’s View Contain built-in or embedded SQL statements At execution time, those SQL statements will be executed by Loading the needed access paths into storage and Completing the missing variables with input from a dataset or terminal. The access path is determined at compilation time, the access logic will always be the same.
  • 13. The Dynamic Program’s View Don’t have complete built-in SQL statements but ask for the SQL statements(or parts of SQL statements such as a WHERE clause) at Execution Time. The access path could not be determined at compilation time since a fundamental part of the statement, or the entire statement, was until execution of the program.
  • 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 for administration . DB2 environment setup need only once. Additional advantage: portability
  • 15. The Internet User’s View Access DB2 without being aware of this fact. Net.data provides the user with the link between the Web page and the database.
  • 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
  • 17. Program’s Responsibility: LUW(Logical Unit of Work) A 2000 1000 1000 1000 B 3000 3000 4000 4000 A 2000 1000 1000 2000 B 3000 3000 4000 3000 Transfers $1000 from account A to account B LUW UPDATE A UPDATE A UPDATE B UPDATE B COMMIT ROLLBACK
  • 18. Program’s Responsibility: Checkpoint / Restart LUW LUW LUW LUW LUW LUW LUW LUW
  • 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
  • 20. The System’s View DB2’S Responsibilies SECURITY CONSISTENCY CONCURRENCY PERFORMANCE METADATA
  • 21. The DB2 Family MAINFRAME servers LAN clients
  • 24. TSO Time Sharing Option Logging on & ISPF Initialization
  • 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:
  • 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 TSO sessions after this will begin with this ISPF screen after the initial logon.
  • 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>.
  • 28. Next: Type ‘2’ at the Option prompt of the Utility Selection Panel then <ENTER>
  • 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’
  • 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.
  • 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.
  • 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’
  • 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
  • 34. The screen below is the result of the ‘S’ request on the ALTTAB member. Z999999.DB2.SPUFI (ALTTAB)
  • 35. NOW to get to DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.
  • 36. Then from the next menu choose option ‘2’ -- DB2I. Now you can start learning DB2!
  • 37.
  • 38. Type ‘2’ to delete without printing Then press <ENTER> to choose SYSOUT class A and exit ISPF
  • 39. Then at the READY prompt, type either LOGOFF to terminate your session or type ISPF to return to ISPF main menu
  • 40. DB2
  • 41.
  • 42.
  • 43.
  • 44. To get to SPUFI in DB2: Type ‘M’ at the Option prompt for the menu of Miscellaneous programs.
  • 45. Then from the next menu choose option ‘2’ -- DB2I. Now type a ‘1’ at the “DB2I PRIMARY OPTION MENU
  • 46. SPUFI’s Main Menu consists of three sections: 1. Information about the input data set 2. Information about the output data set 3. Processing Options (steps SPUFI works through) NOTE: The F1 help of SPUFI is NOT available.
  • 47.
  • 48.
  • 49. If you press <ENTER> after supplying the input and output data 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. **
  • 50. Change Defaults (leave this set to ‘NO’): The change defaults panel allows you to change any of nine options that relate to the processing of input data sets and the format of the resulting output of that processing.
  • 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:
  • 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.
  • 53. MAX NUMERIC FIELD -- maximum width a numeric column of a 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.
  • 54. Edit Edit 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.
  • 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.
  • 56. Pressing F3 during an EDIT session will accept the new input file and return to the SPUFI main menu to execute the next step. ‘ USERID.DB2.SPUFI(SQLPGM)’ PRESS ‘F3’ ‘ USERID .DB2.SPUFI(SQLPGM)’
  • 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.
  • 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.
  • 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.
  • 60.
  • 61.
  • 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.
  • 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.
  • 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:
  • 65.
  • 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.
  • 67.
  • 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>.
  • 69. Press <ENTER> to go to EXECUTE Example 1 continued
  • 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.
  • 72. This is the output from two screens combined. Example 2 continued
  • 73. Example 3: The SQL dataset The Output dataset with the “Count” Displayed
  • 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 )
  • 76.
  • 77.
  • 78. PERSON STUDENT TEACHER Relations in Example Database
  • 89.
  • 90. DB2 Structure Storage Group: STG1 (STOGROUP) DATABASE DB1 INDEX A INDEX C Storage Group: STG2 TABLE A TABLE B Tablespace: TS1 TABLE C Tablespace: TS2
  • 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.
  • 92. DB2 Concept The Hierarchy of DB2 Structures Database D1 Table T1 Table T2 Table space S1 Index X1 Index X2 Table T3 Part 1 Table T3 Part 2 Partitioned Table space S2 Partitioned index X3 Part 2 Partitioned index X3 Part 2 Storage Group G1 3390 Storage Group G2 3380
  • 93. DB2 Concept The Hierarchy of DB2 Structures Storage Group Database Table Space Table Column Index View Alias Synonym
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103. DB2 Concept Physical Design Issue Physical Design Issue Designing 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 &quot;page&quot; size. DESCRIPTION fixed length string variable length string (or longer than 254 char) LENGTH x characters (maximum 254) 0 to x characters (maximum 4K*)
  • 104. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Double byte Data Type DATA TYPE GRAPHIC(x) VARGRAPHIC(x) * Approximately, assuming 4K page. True maximum length depends on lengths of other columns, as well as &quot;page&quot; size. DESCRIPTION fixed length string variable length string (or longer than 127 char) LENGTH x characters (maximum 128) 0 to x characters (maximum 2K*)
  • 105. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Numeric Data Type DATA TYPE SMALLINT INTEGER INT DECIMAL(x,y) DEC(x,y) NUMERIC(x,y) FLOAT(m) REAL FLOAT FLOAT(n) DOUBLE PRECISION * Approximately **1 <= m <= 21, 22 <= n <= 53 DESCRIPTION Whole numbers Whole numbers x digits, of which y are to the right of the decimal point short floating point ** log floating point ** RANGE  32K*  2 Billion up to 32 digits 5.4E-79 to 7.2E+75 5.4E-79 to 7.2E+75
  • 106. DB2 Concept Physical Design Issue Physical Design Issue Designing Columns Date, Time, Timestamp Data Type DATA TYPE DATE TIME TIMESTAMP INTERNAL FORMAT yyyymmdd hhmmss yyyymmddhhmmssnnnnnn (nnnnnn = microseconds)
  • 107.
  • 108.
  • 109.
  • 110. DB2 Concept Physical Design Issue DEPTNO ... C01 DEPTNAME ....... INFORMATION CENTER PRIMARY KEY OPERATIONS ... ... ... ... ... ... E11 DEPARTMENT table FOREIGN KEY EMPNO 000030 000090 000130 000290 000300 .... FIRSTNM SALLY EILEEN DOLORES JOHN PHILIP .... LASTNAM KWAN HENDERSON QUINTANA PARKER SMITH .... ... ... ... ... ... ... ... DEPT C01 E11 C01 E11 E11 ... ... ... ... ... ... ... ... PRIMARY KEY EMPLOYEE table
  • 111.
  • 112. DB2 Concept -- Referential Integrity 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
  • 113. DB2 and Structured Query Language
  • 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
  • 115. DB2 Programming Concept SQL 语言特性 : . 取代传统的 DO PROCEDURE LANGUAGE . 程序设计者 只需 申明 需要 哪些资料 ,不需 申明 如何取得 这些资料 . 不仅是数据查询 工具 ,也能进行数据管理 . 命令语法易学易懂 - SELECT * FROM DA. TBDAMF WHERE APPLID = 'DA'; - UPDATE DA.TBDAMF SET FILE = 'AAAAAA' WHERE EMPNO = '111111';
  • 116. DB2 and Data Definition Language
  • 117. Data Definition Language (DDL) ALTER statement : ALTER STOGROUP ALTER TABLESPACE, ALTER TABLE, ALTER INDEX 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
  • 118. Data Definition Language (DDL) -- CREATE CREATE STOGROUP stogroup-name VOLUMES volume-id VCAT catalog-name PASSWORD password ; CREATE STOGROUP IBMST001 VOLUMES ACA301 VCAT DSNCAT PASSWORD 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
  • 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
  • 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
  • 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.
  • 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.
  • 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
  • 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
  • 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, ….);
  • 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
  • 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 NULL RESTRICT -- if there are tuples in the referenced table, cause an error to occur CASCADE -- 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
  • 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. *** NOTE : 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;
  • 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 ) ….
  • 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
  • 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-name CLUSTER; 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.
  • 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)
  • 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.
  • 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.IBMNX001 ON IBMDB001.TAB001 ( PROJECT-NO ASC) USING STOGROUP IBMSG001 CLUSTER;
  • 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 subselect WITH [ CASCADED | LOCAL ] CHECK OPTION; Privilege Needed: SELECT (on each table or view) or Ownership of the table or DBADM or SYSADM or SYSCTRL
  • 136. 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, EMPLOYEE WHERE EMP-NO = ‘12349’; Page:2-35 Data Definition Language (DDL) -- CREATE VIEW
  • 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
  • 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
  • 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,...); error occurs and no rows are inserted Data Definition Language (DDL) -- CREATE VIEW
  • 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)
  • 141. SYSIBM.SYSTABLES SYSIBM.SYSCOLUMNS SYSIBM.SYSVIEWS SYSIBM.SYSVIEWDP Since views are virtual tables, Db2 will keep information about them 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 (DDL) -- CREATE VIEW ( View Catalog Information)
  • 142.
  • 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 or DBCTRL or SYSADM or SYSCTRL To drop a synonym: Ownership
  • 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 ;
  • 145. DB2 and Data Control Language
  • 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.
  • 147. 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 Data Control Language (DCL)-- GRANT
  • 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 IBMDB001 TO PUBLIC ; Data Control Language (DCL)-- GRANT
  • 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 IBMDB001 TO T90XXX, T90YYY, T90ZZZ, …. ; Data Control Language (DCL)-- GRANT
  • 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
  • 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
  • 152. 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; Data Control Language (DCL)
  • 153. DB2 And DML
  • 154. INSERT statement Inserts 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 Data Manipulation Language (DML)
  • 155. INSERT INTO [ table-name | view-name ] VALUES (.., .., .., .., ..); INSERT INTO [ table-name | view-name ] ( column-name , …, …, ) VALUES (.., .., .., .., ..); INSERT INTO [ table-name | view-name ] subselec t ; INSERT INTO [ table-name | view-name ] ( column-name , …, …, ) subselect ; Data Manipulation Language (DML) -- INSERT
  • 156. INSERT INTO TAB001 VALUES ( ‘00024’ , ‘Mary’ , ‘D11’ , 15 ); INSERT INTO TAB002 ( CUSTOMER-ID, CUSTOMER-NAME, CUSTOMER-ROOM-NUMBER, CUSTOMER-AGE ) VALUES ( ‘00024’, ‘Mary’, ‘D11’, 15 ); INSERT INTO VIEW001 SELECT * FROM TAB003 ; INSERT INTO VIEW002 SELECT * FROM TAB003 WHERE GPA > 3.0; Data Manipulation Language (DML) -- INSERT
  • 157. 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. Data Manipulation Language (DML) -- INSERT
  • 158. 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 Data Manipulation Language (DML)
  • 159. Searched update: UPDATE [ table-name | view-name ] SET column-name = [ expressio n | 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 ; Data Manipulation Language (DML) -- UPDATE
  • 160. UPDATE TAB001 SET PHONE-NUMBER = ‘815-753-6945’ WHERE EMPLOYEE_NUMBER = ‘E293’ ; UPDATE TAB001 SET SALARY = SALARY + 100 WHERE EMPLOYEE_NUMBER = ‘E948’ ; Embedded in COBOL: EXEC SQL UPDATE TAB003 SET SALARY = 2 * SALARY WHERE CURRENT OF CURSOR1 ; END-EXEC. Data Manipulation Language (DML) -- UPDATE
  • 161. 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 Data Manipulation Language (DML) -- UPDATE
  • 162. 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. Data Manipulation Language (DML) -- UPDATE
  • 163. 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 Data Manipulation Language (DML)
  • 164. Searched delete: DELETE FROM [ table-name | view-name ] WHERE search-condition ; Positioned delete: DELETE FROM [ table-name | view-name ] WHERE CURRENT OF cursor-name ; Data Manipulation Language (DML) -- DELETE
  • 165. DELETE FROM TAB001 WHERE DEPT-NUMBER = ‘E11’ OR DEPT-NUMBER = ‘D21’ ; Embedded in COBOL program: EXEC SQL DELETE FROM TAB003 WHERE CURRENT OF CURSOR1 ; END-EXEC. Data Manipulation Language (DML) -- DELETE
  • 166. SQL Statement Performance-access path Access Paths Typical access paths: Table(space) scan Matching index scan No-matching index scan Index-only access The Access Path is determined by the Optimizer in DB2. It can be influenced by the way you write your SQL statement.
  • 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%’
  • 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’
  • 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) S mith,Stanley(8,2) S mith,Steve(8,1) Thompson,Tom(6,3) Zidler,Bob(6,1) Jones,Bob Reeves,Susan Peters,Joan Adams,Mark Mitchell,David Bennett,Barb Davis,Mac Howell,Thurston . Jefferson,Tom Lee,Spike . Champman,Mike Adams,Mark . Zidler,Bob Quinn,Tonny Thompson,Tom Lincoln, Abe Alvani,Cart . S mith,Steve S mith,Stanley . Data Pages Root Page Leaf Pages
  • 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
  • 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
  • 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
  • 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
  • 174. INDEXED Column is... DB2's USE OF INDEXES Used with: IN LIKE BETWEEN >,>=,<,<=,  >,  <,=  =,<> NOT OR ORDER BY GROUP BY DISTINCT^ Compared to: longer literal arithmetic exp. diff. data type Used for JOIN INDEX Candidate YES NOTE1 YES YES NO NOTE2 NOTE3 YES YES YES NO NO NO YES Sort Candidate YES YES YES YES NOTE1 : YES, except when string is host-variable, or string is of the form '%...' or '-...' NOTE2 : Apply NOT, then evaluate NOTE3 : NO unless convertible to in DB2 -- SQL Statement Performance
  • 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
  • 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
  • 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
  • 178. BATCH TSO and DB2 EMBEDDED SQL
  • 179.
  • 180.
  • 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
  • 182. Source Program Precompiler DCLGEN DBRM Modified Source Compiler Compiled Source Linkage Editor Load Module Bind Package Package Bind Plan Plan DB2 Catalog DB2 Directory DB2 Embedded SQL -- Program Preparation
  • 183.
  • 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. DVLP.BOOKLIB(EMPXXRCD) Embedded SQL -- DCLGEN
  • 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. To Use DCLGEN , select option 2 from the DB2I Primary Option Menu. EMP99 EDUCS99 ‘ DVLP.BOOKLIB(EMP99RCD)’ EMP99DCL Embedded SQL -- DCLGEN
  • 186. Option 1 : SOURCE TABLE NAME The 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. EMP99 DVLP Embedded SQL -- DCLGEN
  • 187. Option 4: DATA SET NAME Here 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 PASSWORD If the data set has a password, specify it here. ‘ DVLP.BOOLIB(EMP99RCD)’ Embedded SQL -- DCLGEN
  • 188. Option 6 : ACTION Specifies 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
  • 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. Option 8 : STRUCTURE NAME Uses 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 Embedded SQL -- DCLGEN
  • 190. Option 9 : FIELD NAME PREFIX Specifies 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. EMP99DCL Embedded SQL -- DCLGEN
  • 191.
  • 192.
  • 193. SQL Communication Area - SQLCA SQL Stmt SQLCA Program checks returned values Execute SQL stmt and Updates the Comm Area Program DB2 SQLCODE
  • 194.
  • 195. 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). Embedded SQL -- SQLCA
  • 196. 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. DB2 Embedded SQL -- Program Preparation
  • 197.
  • 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
  • 199. 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. Program Preparation-Precompile
  • 200.
  • 201.
  • 202.
  • 203. Package: 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 DB2 Embedded SQL -- Program Preparation
  • 204. DBRM BIND PACKE(collx) MEMBER(dbrma) BIND PACKE(colly) MEMBER(dbrma) colly dbrma dbrmb Dbrm... Package name= collection_id.package_id PACKAGE collx dbrma dbrmb Dbrm...
  • 205. A collection is a set of packages. A package is bound in a collecion. A collection is implicitly created at first BIND PACKAGE referring to that collection. Example: BIND PACKAGE( online ) MEMBER(pkg1) BIND PACKAGE( batch ) MEMBER(pkg3) Collection(packageset) online pkg1 pkg2 batch pkg3 pkg4
  • 206. 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) Collection(packageset) test_payroll pkg1 pkg2 prod_payroll pkg1 pkg3
  • 207. Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,  ,2) ... Mprog1 ... call DSNHLI ( dbrm2 ,  ,1) ... Call  Call  call  DB2 Directory colly dbrm1  ? Page:3-44 Locating PACKAGEs at execution time collx dbrm1  dbrm3  collz dbrm2  dbrm4 
  • 208. Mprog1 call DSNHLI ( dbrm1 ,  ,1) ... call DSNHLI ( dbrm1 ,  ,2) ... Mprog2 ... call DSNHLI ( dbrm2 ,  ,1) ... Call  Call  call  DB2 Directory colly dbrm1  Page:3-44 Collx.dbrm1,collz.* plana BIND PLAN(plana) Pklist(Collx.dbrm1,collz.*) Locating PACKAGEs at execution time collx dbrm1  dbrm3  collz dbrm2  dbrm4 
  • 209. 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. Locating PACKAGEs at execution time
  • 210. 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 PLAN A 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 ) PLAN and PACKAGEs
  • 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.SYSTABLES SYSIBM.SYSTABLESPACE SYSIBM.SYSTABSTATS SYSIBM.SYSUSERAUTH Information about plans is then stored in the following tables: SYSIBM.SYSDBRM SYSIBM.SYSPACKAUTH SYSIBM.SYSPACKLIST SYSIBM.SYSPLAN SYSIBM.SYSPLANAUTH SYSIBM.SYSPLANDEP SYSIBM.SYSPLSYSTEM SYSIBM.SYSSTMT SYSIBM.SYSTABAUTH PLAN and PACKAGEs
  • 212. BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*) BIND PLAN(plana) PKLIST(Collx.dbrm1,collz.*) MEMBER(dbrma,dbrm1) BIND PLAN(plana) MEMBER(dbrma,dbrm1) collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2   Instream DBRM BIND PLAN - DBRMS
  • 213. collx.dbrm1,collz.* plana collx.dbrm1,collz.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,  ,1) ... Instream DBRM first! PACKAGE Search
  • 214. collx.dbrm1,colly.* plana collx.dbrm1,colly.* planb dbrma  dbrm1  planc dbrm1  dbrm2  ... CALL DSNHLI(dbrm1,  ,1) ... Sqlcode: -818 Sqlcode: -805 colly dbrm1  Timestamp Mismatch Errors
  • 215. TSO RUN PROGRAM( mprog1 ) PLAN( plana ) CICS RCT(Resource Control Table) IMS RTT(Resource Translate Table) CAF Callable Interface(DSNALI) RRSAF DSNRLI Running the Program
  • 216. Each execution environment has its own language interface LINK-EDIT
  • 217. ... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE QUAL(TEST) BIND PACKAGE QUAL(PROD) BIND PACKAGE TEST .TAB1 binder .TAB1 PROD .TAB1 binder BIND PACKAGE OR PLAN BIND - QUALIFIER Option
  • 218. ... SELECT ... FROM TAB1 ... dbrm BIND PACKAGE(usdcol) QUAL(usd) USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PACKAGE(yencol) QUAL(yen) dbrm1  yencol Same structure TABLE Mirroring-1
  • 219. ... SELECT ... FROM TAB1 ...  USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-2
  • 220. coll = ‘yencol’ . SET CURRENT PACKAGESET=:coll . SELECT ... FROM TAB1  USD .TAB1 YEN .TAB1 dbrm1  usdcol BIND PLAN(plan1) Pklist(usdcol.*,yencol.*) dbrm1  yencol lmod1 usdcol.*, yencol.* plan1 TABLE Mirroring-3
  • 221. 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 Special Register- CURRENT PACKAGESET
  • 222. pgma  UTTEST.SRC Precompile version (uttest) Precompile version (systest) pgma  UTTEST.LOAD pgma  SYSTEST.LOAD BIND PACKAGE(collx) MEMBER(pgma) pgma  collx pgma  pgma  UTTEST.SRC PACKAGE VERSIONING
  • 223. RR (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 COMMIT S or ROLLBACK S.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. Data Consistency- Isolation Level
  • 224. 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 ). Data Consistency-Isolation Level
  • 225. 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. Data Consistency-Isolation Level
  • 226. 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. Data Consistency-Isolation Level
  • 227. 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. Data Consistency-Isolation Level
  • 228. 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. DB2 Embedded SQL -- Program Preparation
  • 229. 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 FREE / DROP
  • 230.
  • 231. DB2 AND COBOL DB2 & COBOL
  • 232. DB2 Programming Concept DB2 Ap p l i c a t i o n S t r u c t u r e DB2 Ap p l i c a t i o n S t r u c t u r e ․ WORKING STORAGE SECTION - INCLUDE TABLE STRUCTURE - INCLUDE SQLCA - CURSOR DECLARATION ․ PROCEDURE DIVISION - ERROR HANDLING - DML SQL STATEMENT - CURSOR HANDLING - CHECK SQLCODE
  • 233. Two types or embedded SQL statements: 1. Singleton SELECTs -- MUST select only ONE row. And MUST contain INTO clause. Here the names of the host variables that will accept the data returned by DB2 are listed. 2. Cursor SELECTs -- Processes multiple rows. Embedded SQL
  • 234.
  • 235.
  • 236. What you DON’T code for a DB2 Table: 1. A COBOL SELECT statement 2. A File Description entry 3. A Record Description What you DO or CAN code: 1. INCLUDE statement for SQL Communications Area 2. Table Declarations 3. Host Variables 4. Cursors Embedded SQL
  • 237.
  • 238. 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). Embedded SQL -- SQLCA
  • 239.
  • 240.
  • 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
  • 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
  • 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. DATE 2. SMALLINT 6. TIME 3. INTEGER 7. TIMESTAMP 4. DECIMAL Embedded SQL -- Host Structures
  • 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
  • 245. When using host variables in SQL statements, you must precede the host variable name with a colon( : ). Example: EXEC SQL SELECT FNAME, LNAME, ADDRESS INTO :FNAME, :LNAME, :ADDR FROM PERSON WHERE 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
  • 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
  • 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
  • 248. Processing Multiple Rows EMPNO LASTNAME 000030 000290 000300 KWAN PARKER SMITH . 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 until break Embedded SQL -- Cursors
  • 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
  • 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
  • 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 a DECLARE 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
  • 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 SQL OPEN INSTCURS END-EXEC. OPEN is coded in the PROCEDURE DIVISION . Embedded SQL -- Cursors
  • 253. Closing a Cursor CLOSE statement releases the results table associated with the specified cursor. EXEC SQL CLOSE 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
  • 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 SQL FETCH INSTCURS INTO :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
  • 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
  • 256. EXEC SQL DECLARE CX CURSOR FOR SELECT EMPNO, LASTNAME FROM EMP99 WHERE DEPTNO = :DPT FOR UPDATE OF LASTNAME END-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
  • 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
  • 258. COMMIT - CURSOR REPOSITIONING EXEC 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
  • 259.
  • 260. 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. Cursors-- Optimize for n Rows
  • 261.
  • 262.
  • 263. SELECT statement In PROCEDURE DIVISION: EXEC SQL SELECT column-specification, [ column-specification, … ] INTO : host-var, [: host-var… ] : host-structure FROM table-name, [ table-name,… ] [ WHERE selection-condition ] END-SQL. Embedded SQL -- Select
  • 264. column-specification A description of what the SELECT statement should put in the corresponding results table EXEC SQL SELECT column-specification, [ column-specification, … ] Embedded SQL -- Select
  • 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
  • 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
  • 267. Example: Say you have the following FNAME data in the person table: BOB GREEN MARY WHITE JANE SMITH To return the first and last name of a person with the first name “BOB”, you execute the statement: EXEC SQL SELECT LNAME, FNAME INTO :LNAME, FNAME FROM PERSON WHERE FNAME = ‘BOB’ END-EXEC. When this SQL statement executes, it returns a one row results table: BOB GREEN Embedded SQL -- Select
  • 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 SQL FETCH NAMEINFO INTO :FNAME, :LNAME END-EXEC. Embedded SQL -- Select
  • 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
  • 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 USER Extracts the current user id from the DB2 catalog and adds it to the results table. Embedded SQL -- Select
  • 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 - :TAX Character 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
  • 272. FROM clause The 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 clause The INTO clause of the SELECT statement names the COBOL host variables into which DB2 will place the results table data. SELECT FNAME, LNAME INTO :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
  • 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