View
228
Download
0
Category
Preview:
Citation preview
8/8/2019 DB2 Basics - Quick Refernce
1/29
Mainframe For Dummies
DB2 Basics - Quick Refernce
Relational Database Management System(RDBMS) Universal Database(UDB)
This is one of the sub systems in Mainframes.
Any number of Sub Systems can be created in Mainframesas per the requirements.
Hierarchy of DB2 Sub system:
http://mainframe-faqs.blogspot.com/http://mainframe-faqs.blogspot.com/2008/02/db2-basics-quick-refernce-relational.htmlhttp://mainframe-faqs.blogspot.com/http://mainframe-faqs.blogspot.com/2008/02/db2-basics-quick-refernce-relational.html8/8/2019 DB2 Basics - Quick Refernce
2/29
TS Table Space INS Index Space
T Table IND Index
V view
Maximum storage space for a Table Space is 64 millionbytes.
SQL can be used to Create, Delete, and Update and Querythe Objects
SQL queries can be executed by the following techniques
8/8/2019 DB2 Basics - Quick Refernce
3/29
1. Application programming2. Tools like QMF (Query Management Facility)
SPUFI (SQL Processor User File Input)
DATA TYPES :
Integer -- 4 bytes
Small int -- 2 bytes
Char(n) N bytes
Varchar(n) N+2 bytes
Graph(n) 2n bytes
Vargraph(n) 2N+2 bytes
Date 10 bytes
Time 8 bytes
Timestamp 26 bytes
NORMALIZATION :
Arranging the data in the Database in organized manner.
1NF: Avoiding multiple values or set of values in one column.
2NF: Avoiding repeated rows by defining primary key.
3NF: Separating functionally dependent and non-functionallydependent columns
8/8/2019 DB2 Basics - Quick Refernce
4/29
Primary key :-
Uniquely identified row Which can be formed with single or multiple columns Does not allow duplicate records Cannot contain Null
Foreign key : -
Another identifier which can be used to buildrelationship between the tables
Must be the primary key of parent table with same datatype & length
Can consists of single or multiple columns Can contain Null or duplicate rows Multiple foreign keys can be defined in one table Foreign key should be defined at the time of defining
child table in the create command by WITH
REFERENCES option.
CREATE TABLE ITEM(
INO INTEGER,
INAME CHAR(15),
CNO INTEGER,
PRIMARY KEY IS INO,
FOREIGN KEY IS CNO
WITH REFERENCES CUST)
8/8/2019 DB2 Basics - Quick Refernce
5/29
REFERENCE INTEGRITY:
The relationship between two tables which can beachieved by defining foreign key.
PRIMARY KEY FOREIGN KEY
Cannot contain Null values orduplicate rows
Can contain Null values orduplicate rows
Cannot be updated Can be updated
Can be defined as a foreignkey in other table
which must be primary key ofanother table
only one primary key can bedefined for one table
multiple foreign keys can bedefined for one table
SQL(Structured Query Language)
DDL (Data Definition Language)
Create, alter, drop
8/8/2019 DB2 Basics - Quick Refernce
6/29
DML (Data Manipulation Language)
Insert, update, select & delete
DCL (Data Control Language)
Grant, Revoke
TCL (Transaction Control Language)
Commit, Rollback
Some SQL Quries
Static SQL for Insert: Insert into cust(cno, cname, cloc)
values (10, xyz, hyd)
Dynamic SQL for Insert: Insert into cust(cno, cname, cloc)values (v1, v2, v3)
v1,v2, v3 are host variables to be defined in working storagesection.
Delete from cust
Delete from cust where cno = 20
8/8/2019 DB2 Basics - Quick Refernce
7/29
Update cust set cname = xyz where cno = 20
Select cno,cname from cust
Select * from cust
Select * from, cust where cno = v1
Select * from cust wehre cno=v1 and cname =v2
Select * from cust where cno between 20 and 60
Select * from cust where cname like %y%
Column functions:
Select max(sal) from emp
Select min(sal) from emp
Select avg(sal) from emp
Select sum(sal) from emp
Above statement returns Null values if no row exits for
specified condition
To avoid duplicate rows : select distinct cno,cname from cust
To get total no. of rows : select count(*) from cust
8/8/2019 DB2 Basics - Quick Refernce
8/29
Above statement returns Zeros if no row exits for specifiedcondition
SUBQUERY:
Query within Query First inner query executes & out query executes based
on the result of inner query Max of 15 sub queries can be coded To simplify sub queries, logic can be built with
combination of COBOL + SQL statements
To retrieve second maximum salary from emp table:
Select max(sal) from emp where sal
8/8/2019 DB2 Basics - Quick Refernce
9/29
8/8/2019 DB2 Basics - Quick Refernce
10/29
Host variables:
Can be used to pass the data from cobol program toDB2 table or DB2 table to COBOL program.
When host variables are coded with sql statements itmust be prefixed with : like :hv-cname.
Table name must be supplied as input to DCLGEN &partition dataset should be as output.
After creating DCLGEN variables which must be copiedto application program in WORKING-STORAGE SECTIONby using include command i.e.
Exec sql
Inlcude custDCL
End-exec.
Include & copy have the same functionality
SQLCODE :
Predefined numeric number which can be used to checkSQL statements for successful , unsuccessful execution.
SQLCODE can be stored in SQLCA(SQL CommunicationArea) Copy SQLCA in WORKING-STORAGE SECTION System defined variable Evaluate or if statement must be coded to check the
SQLCODE immediately after SQL statement. SQLCODE =00 ---- successful
8/8/2019 DB2 Basics - Quick Refernce
11/29
= +100 --- end of table or record not found.
Sample program:
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE SQLCA
END-EXEC
EXEC SQL
INCLUDE CUSTDCL
END-EXEC.
01 WS-SQL-CODE PIC S9(4)
88 88-SUCCESS VALUE 00
88 88-NOTFOUND VALUE 100
88 88-FORIENG KEY VOILATION VALUE 532
88 88- MULITPLE ROW VALUE 811
8/8/2019 DB2 Basics - Quick Refernce
12/29
PROCEDURE DIVISION.
UPDATE CUST
SET CNAME = :HV-CNAME
WHERE CNO=:HV-CNO
MOVE SQLCODE TO WS-SQLCODE.
EVALUE WS-SQL-CODE
WHEN 88-SUCCESS
DISPLAY SUCCESSFULLY UPDATED
WHEN 88-NOTFOUND
DISPLAY RECORD NOT FOUND
WHEN 88-FOREIGNKEYVOILATION
DISPLAY FOREIGN KEY VOILATION
WHEN OTHER
DISPLAY ERROR OCCURRED IN UPDATE
STOP RUN
END-EVALUATE.
STOP RUN.
CURSOR:
8/8/2019 DB2 Basics - Quick Refernce
13/29
To retrieve multiple rows for a given condition.
Let us take the following example:
Exec sql
Select cno,cname,cloc
into :hv-cno,:hv-cname,:hv-cloc
from cust where cloc =:hv-cloc
end-exec.
If the condition satisfy for one row it executes successfully. Ifthe condition satisfy for multiple rows it wont work. It returns811 as SALCODE. For this we use cursors.
Cursors can be used to retrieve multiple rows for agiven condition
Cursor cycle is Declare ---> Open ----> Fetch ----->Close
Declare: declares or define name for cursor against atable
Can be coded in working-storage section or procedure
division
For better readability code in working-storage section.
Open:can be used to open a cursor with rows for agiven conditions inbuffer.
Retireves data in to buffer
8/8/2019 DB2 Basics - Quick Refernce
14/29
Must be coded in the procedure division only
Where condition value must be supplied beforeopening a cursor.
Fetch:can be used to retrieve rows one by one frombuffer into application prog.
Which must be coded in procedure divison afteropen.
Must be coded with hostvariables
No of host variables in fetch & no of columns inthe declare must be same
Canbe executed multiple times using perform. i.e.till EOT or record not found which can be identifiedby SQLCODE = 100
Close :used to close the cursor
Must be coded in procedure division only
Must be executed after open statement.
Practical examples : Can be used to retrieve the databased on loc, date, products.
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT CNO,CNAME FROM CUST
WHERE CNAME=:HV-CNAME
8/8/2019 DB2 Basics - Quick Refernce
15/29
END-EXEC.
EXEC SQL
OPEN C1.
END-EXEC.
PERFORM UNTIL SQLCODE= 100
EXEC SQL
FETCH C1 INTO :HV-CNO,:HV-CNAME
END-EXEC
END-PERFORM.
EXEC SQL
CLOSE C1
END-EXEC
For Update of where current of:
Which can be used to update row by row when multiplerows are satisfied.
Before update cursor has to be declared with for updateof column option.
Where current of cursor name option must be used with
update command Withhold: this option can be used to remain cursors
open even after commit statement. Must be coded with cursor statement
8/8/2019 DB2 Basics - Quick Refernce
16/29
EXEC SQL
DECLARE C2 CURSOR WITH HOLD FOR
SELECT CNO,CNAME FROM CUST
WHERE CNAME=:HV-CNAME
FOR UPDATE OF CNAME
END-EXEC.
EXEC SQL
OPEN C1.
END-EXEC.
EXEC SQL
FETCH C2 INTO :HV-CNO,:HV-CNAME
END-EXEC
EXEC SQL
UPDATE CUST SET CNAME=ABC WHERE CURRENT OFC2.
EMD=EXEC.
EXEC SQL
CLOSE C1
END-EXEC
INDEX:
8/8/2019 DB2 Basics - Quick Refernce
17/29
Index allows duplicate values unique index doesnt allow duplicate rows cross reference between index table & table is called
clustered index. Create index in1 on cust(cno)
PRIMARY KEY INDEX UNIQUE INDEX
Uniquelyidentified row
Record identifiedbased on the index
Recordsidentified basedon the index
No duplicatedrows, no nullvalues
Duplicate rows, nullvalues are allowed
No duplicaterows
Can consist ofsingle or multiplecolumns
Dan consist ofsingle or multiplecolumns
Can consist ofsingle orcolumns
This will bestored inSYSKEYS.
This is stored inSYSINDEX
This is stored inSYSINDEX
VIEWS:
8/8/2019 DB2 Basics - Quick Refernce
18/29
CREATE VIEW CVIEW(VCNO,VCNAME,VCLOC) AS
(SELECT CNO,CNAME,CLOC FROM CUST WHERE
CNAME LIKE %X%)
Logical representation of the table Stored in virtual memory Can be derived from single table or multiple tables Views are updateable if they are derived from single
table without any column functions , group by Multiple views can be generated from single table.
Views are stored in sysviews
Advantages of Views:
Data security Data correctness
Logical data independence Part of the information can be visible to the sers Accessing can be faster.
DELETE RULES:
Delete rules can be applied for delete command againstDatabase.
Delete rules are 3 types
8/8/2019 DB2 Basics - Quick Refernce
19/29
1. on delete cascade all matching child rowswill be deleted automatically when we deleteparent row.
2. on delete restrict all matching rows will be
restricted when we delete parent row whichis default.3. on delete set null all matching child row will
be set to null when we delete parent row.
UNION:
UNION is used to concatenate rows into one table fromsingle or multiple tables.
Rules : no. of columns & data type of both the queriesmust be same. column may be different
UNION can be used to eliminate duplicate rows UNION ALL retrieved duplicate rows also.
SELECT CNO,CNAME FROM CUST WHERE CNO=10
UNION/UNIONALL
SELECT CNO,CNAME FROM ITEM WHERE INO=20
JOINS:
JOINS can be used to concatenate columns from onetable or multiple tables.
JOIN types are :
8/8/2019 DB2 Basics - Quick Refernce
20/29
1. left outer join : which can be used to retrievematching, non matching rows from leftsidetable
2. right outer join: which can be used to retrieve
matching, non matching rows from right sidetable.3. full outer join: which can be used to retrieve
matching, non matching rows from both thetables.
4. self join or inner join : can be achieved bydefining alias for the table.
EXPLAIN :
It can be used to evaluate the performance of SQL queries.
It can be used to tune SQL queries.
Input is SQL queries and output is plan-table.
For every SQL query one plan-table will generate.
All plan-tables are stored in physical seq file.
Plan table
Query
blockno
Table
Name
No.of
Cols
index
no.of
indexs
owner
jointype
groupby
Cpu
time
8/8/2019 DB2 Basics - Quick Refernce
21/29
1 Cust 10 In1 1 Custc Self Y 10min
DB2 CATALOG:
Consists of Table pace, Index space, Index, uniqueindex, Views, Alias, synonyms, keys.
When we create table, the details of table are enteredin Systable automatically.
SysIBM.SYSTABLE
TableName
No.ofcols
Ownername
Createdby
Createddate
Createdtime
Cust 10 Abc Xyz 02-apr-2004
0850
Item 15 Mno Rst 06-apr-2004
1020
SysIBM.SYSINDEX
8/8/2019 DB2 Basics - Quick Refernce
22/29
Indexname
TableName
No.ofcols
Ownername
Createdby
Createddate
Createdtime
In1 Cust 10 Abc Xyz 02-apr-
2004
0850
In2 Item 15 Mno Rst 06-apr-2004
1020
SysIBM.SYSCOLS
Col name Tablename
Indexname
Primarykey
Foreign key
Cno Cust In1 Cno -----
Cname Cust In1 Cno
Cloc Cust In2 cno
Ino Item Ino Cno
Iname Item Ino Cno
Ides Item Ino cno
SysIBM.SYSKEYS: All primary & foreign keys.
Grant table syscols to all
Grant table syscols(select/delete/update) to user1,user2
Revoke table syscols from all.
8/8/2019 DB2 Basics - Quick Refernce
23/29
CATALOG:
SYSTABLE, SYSCOL, SYSKEYS, SYSINDEX, SYSPKS, SYSFKS,SYSALIAS, SYSSYNONYMS, SYSINDEX,SYSVIEWS,SYSTABLESPACE, SYSINDEXSPACE.
PRECOMPILATION PROCESS:
Pre compiler takes COBOL+DB2 program as input &generates DBRM which will be stored in userdefined PDS asseparate member of Recln=80
DSNHPC --- IBM supplied utility used forprecompilation.
Precompiler functions:
Separates SQL & COBOL statements Check SQL syntaxs Replace all SQL statements with host language call
statements in the compiled program. Which generates timestamp tokens
BIND:
8/8/2019 DB2 Basics - Quick Refernce
24/29
BIND takes DBRM as input & generate package & applicationplan. The package will be loaded to the directory. Plan will beloaded to sysplans.
Bind functions:
Checks authorization for SQL statement Checks the syntax errors of SQL statements like
1. Missing co name in the select list & used in order by &group by
2. Mismatch columns host variables3. Data type mismatch of columns & host variables4. Indicator variables not declared5. Data truncation.
BIND SUBCOMPONANTS/PARAMETERS:
1. OPTIMIZER:o It generates optimized access path by analyzing
the statistics of SQL statements which will bestored.
o RUNSTATS utility is one of the ISPF panel optionwhich is stored in DB2 defaults option.
o Optimized path is stored in package which is notexecutable module.
2. ISOLATION LEVEL:
Which can be used to lock the database at the time ofexecuting SQL statements.
8/8/2019 DB2 Basics - Quick Refernce
25/29
Cusrsor stability(CS): It acquires the address of a row.Sets the pointer to a specified row based on SQL query& acquires the lock against that row. Then releases theklock after the transaction before commit.
Repeatable Read(RR): which acquires the address of arow & acquire lock against the page(1 page -4024bytes) & then released the lock after the commitstatements.
Default is RR.
3. RUNTIME SUPERVISOR:
Which is to oversee execution of SQL statements.
Statistics like no of tables, columns, indexes, keys
4. PLAN/APPLICATION PLAN:
It consists of executable module which is actual outputof SQL statements which must be specified in theRUNJCL to execute SQL queries if the program is batchprogram. If the program is online which must be
specified in RCT. Application plan will be loaded to loadmodule with time stamp tokens.
COBOL COMPILATION:
8/8/2019 DB2 Basics - Quick Refernce
26/29
The compiler takes COBOL statement as input to generateobject program, & loaded to the load module by line/editwith time stamp tokens.
UTILITIES USED:
DSNHPC : system utility pre compiler.
IKJEFT01 or IKJEFT01B --- BIND /Run Cob-DB2 Program
IGYCRCTL or IKFCBLOO --- COBOL compilation
8/8/2019 DB2 Basics - Quick Refernce
27/29
IEWL or HEWL --- link/edit
INTERVIEW QUESTIONS:(watch this space for moreinfo on below Qns)
1. What is RI ? where did u use RI in your project? Explainwith example?
2. What is the difference between primary key, foreignkey, index & unique index?
3. Can we create index when table has duplicate rows?4. Can we create unique index when table has duplicate
rows?5. Can we create index or unique index on empty table?6. What happens to the package when index is dropped?
Whats the process or steps to be taken?7. How to delete package?8. Where package is stored? How to retrieve package?9. Difference between plan & package?
10. What are the steps to be taken when SQLstatements are changed without changing any COBOLstatements?
11. Do we need to pre compile when index isdropped?
12. Can we bind when table is dropped?13. Can optimized access path consist of multiple
DBRMS.14. What is the significance of timestamp tokens?
15. What is the significance of normalization?16. Where do we specify run program, plan name,library & DB2 subsystem
17. IBM supplied utility to run COBOL + DB218. What is difference between DB2 & COBOL files &
give some example for COBOL files & DB2 tablesrelated to your project?
8/8/2019 DB2 Basics - Quick Refernce
28/29
19. Can we load data from sequential file to table ortable to sequential file?
20. What are the steps to be followed to developDB2+ COBOL program?
21. Can we prepare a program/compile when DB2system is down?22. How to identify DB2 test or production system by
seeing run JCL?23. What is the output of explain?24. What is the difference between correlated sub
query & sub query?25. How to find 4th max sal?26. How to find nth max sal?27. How to evaluate SQLcodes & where it is stored?
28. How to count total no of unique rows from thetable?
29. How to sum repeated rows?30. How to write a cobol program for above query?
Retrieve row by row & use cobol logic to sum repeatedrows?
31. What is the significance of DCLGEN?32. Where DCLGEN is stored?33. Difference between join & union?
34. difference between UNION & UNIONALL?35. Can be have different col names in union?36. How do u evaluate/tune/analyze SQL queries?37. What are the JCL utilities for compile, pre compile,
bind & link edit?38. Wha5t is the significance of isolated levels?39. Can we alter foreign key?40. Can we alter primary key?41. Can we alter data type & length?42. What are the equivalent cobol variables for
varchar?43. What is the time stamp & its format?
8/8/2019 DB2 Basics - Quick Refernce
29/29
Recommended