05 08 12 18 26 30 35 42 44 47 58 59 63 65 70 76 79 82










commonly referred to as DB2.A value may be a text string . the formal names for the elements of a relation are tuple (row) and attribute(column). The name relational database comes from the technical term for a table .which may have one . The intersection of a row and a column is a value . But these aren’t the only terms. became generally available in the fall of 1983. Db2 is a database management system. In a relational system • • • • • • • • Data is perceived by users as a collection of tables called relations Operators generate new tables from old ones The rows are referred to as tuples Columns are referred to as attributes Each row in a relation is distinct i. The DBMS is an additional layer of software between the program and the stored data . A row is called a record and a column is called a field. HOW DOES DB2 ORGANIZE AND ACCESS INFORMATION. a relation . an attribute or a combination of attributes whose value uniquely identifies the rows. a number or nothing (null value).many or no rows. A relation may also contain foreign keys which reference other relations in a database. -5- D4 .they are processed differently . A more complete description is that db2 is a relational database management system that uses the industry standard Structured Query Language (SQL) as a central component . A Database management system (DBMS) is a software package that manages data stored in databases. A relational database system presents all information in the form of tables. It uses tables to represent the data that it manages . Entire information content of the database is represented as explicit data values (as explicit values in column positions within rows of a table) DB2 IBM’S Database 2 . DB2 was marketed as a relational database management system for the MVS operating system. You use a DBMS to control and use the information stored on your computer system more effectively and efficiently than you can with standard file processing.e duplicate rows are not allowed Each relation must have a primary key. the unit of processing is a an individual record while in db2 it is an entire table .It’s the DBMS rather than the application program that has a complete picture of the physical and the logical structure of the data stored.DB2 What is a Data base Management System. in standard file processing . In addition . Although files and tables have similar structures . A table is just a two dimensional array with horizontal rows and vertical columns.

DB2 DB2 ARCHITECTURE DB2 as perceived by an individual User user Virtual SQL VIEW1 VIEW2 Real Base Table B1 Stored VSAM Dataset D1 B2 B3 B4 D2 D3 D4 -6- .



The total collection of stored data is divided up into a number of disjoint databases . Each database is divided into a number of disjoint spaces – several table spaces and index spaces. A space is a dynamically extendable collection of pages ,where a page is a block of physical storage (it is a unit of i/o i.e the unit transferred between primary and secondary storage in a physical i/o operation. The pages are given size of either 4k or 32 k. Each table space contains one or more stored tables . a stored table is is a physical representation of a base table .

A Database in DB2 is a collection of logically related objects –that is a logical collection of stored tables that belong together in some way ,together with their associated indexes and the various spaces that contain those tables and indexes . it thus contains a set of table spaces (each containing one or more stored tables ) together with a set of index spaces (each containing exactly one index). A given stored table and all its associated indexes must be wholly contained within a single database. Objects are grouped together into the same database primarily for operational reasons .Tables can be moved from one database to another without having any logical impact on user or user programs.

A table space can be thought of as a logical address space on secondary storage that is use to hold one or more stored tables (logical because it is typically not just a set of physically adjacent areas) . As the amount of data in those table grows (or as the number increases), so storage will be acquired from the appropriate storage group and added to the table space accordingly. One table space can be approx. 64 billion bytes in size and there is effectively no limit to the number of table spaces in a database ,nor to the no. of databases . Fundamentally the table space is the storage unit for recovery and re-organization purposes; i.e. it is the unit that can be recovered via the recover utility . If the table space is very large , however , recovery and re-organization could take a very long time.DB2 therefore provides the option to partition a large table space into simple , partitioned and segmented forms. A simple table space can contain more than one stored table , though one is usually the best option. One reason for having more than one is that stored records for different stored tables can be clustered together in such a way as to improve access times to logically related data. In particular , certain join queries would then be handled more efficiently since the I/O operations would be reduced. Partitioned table spaces are intended for stored tables that are sufficiently large. A partitioned table space thus contains exactly one stored table , partitioned in accordance with value ranges of a partitioning columns or column combination. Individual partitions of a partioned table space are independent of each other in the sense that they can be independently recovered or reorganized. They can also be associated with different storage groups i.e. it is possible to store different partitions on different devices and thereby spread the table space I/O load.



Like simple table spaces, they can contain any number of stored tables ;unlike simple table spaces , however, segmented table spaces do not support any kind of cross table clustering- that is they do not allow records for different stored tables to be interleaved on a single page. Instead , they keep the tables physically separated.

An index space is to an index what a table space is to a stored table. However, since the correspondence between indexes between indexes and index spaces is always one to one, there are no data definition statements for index spaces; instead, the necessary index space parameters are specified on the corresponding index definition statements. Thus for e.g. there is no create index space; instead the index space is created automatically when the corresponding index is created. Like Table spaces ,index spaces can be reorganized and recovered independently.

Index in db2 are based on a structure known as B-tree. A b-tree is a multilevel, tree structured index with the property that the tree is always balanced; i.e. all its leaf entries in the structure are equidistant from the root of the tree, and this property is maintained as new entries are inserted into the tree and existing entries are deleted. As a result, the index provides uniform and predictable performance for retrieval operations. A given table can have any number of associated indexes. Also if the installation follows our recommendation that every base table have a primary key, then every stored table will have at least one index, namely the primary index. To perform an exhaustive search on a given stored table according to a given index, the data manager will access all records in that stored table in the sequence defined by that index and since that sequence may be quite different from the stored table’s physical sequence, a given data page might be accessed many times. It follows that an exhaustive search via a physical sequence unless the index concerned is a clustering index for which the sequence defined by the index is the same as, or close to, the physical sequence. The index is used to control the physical placement of the indexed records. Clustering indexes are extremely important for optimization purpose. The optimizer will try to choose an access path that is based on a clustering index, if one is available, and if clustering sequence is appropriate for the sql under consideration.



A storage group is a named collection of direct access volumes, all of which are the same device type. Each table space and each index space normally has an associated storage group. When storage is needed for the space or partition , it is taken from the specified storage group. Within each Storage group, spaces and partitions are stored using VSAM linear data sets .

Is an alternate name for a base table or view. Each user can assign his or her own synonyms for any table or view that was created by some other fully qualified name.

It is a predefined selection of data in base tables. It is a virtual table that does not physically exist but is processed as a table. It is derived from one or more base tables, or views or combinations of views and tables. The view definition is stored in the DB2 catalog. Changes to the data in the view can change the data in the base table.

Contains information about every DB2 object that is maintained by it. Whenever a DB2 object is created, dropped or altered by any ddl statement or whenever control over the object is changed by any dcl statement of sql, an entry is made in the appropriate catalog table. Catalog table can be accessed using sql, they however cannot be updated by a user(but done so by the system). To retrieve information from the DB2 catalog, the select privilege on the catalog is needed. Some of the catalog tables are : • SYSTABLES • SYSSTOGROUP • SYSTABLESPACE

- 10 -



- 11 -

12 - .DB2 SYSTEM STRUCTURE: The major components of DB2 are • SYSTEM SERVICES • LOCKING SERVICES • DATABASE SERVICES RELATIONAL DATABASE SYSTEM MVS OPERATING SYSTEM TSO Subsystem IMS Subsystem DB2 Subsystem RESOURCE LOCK MANAGER Isolate Users Locking Services DATABASE SERVICES Access Data Create Objects DB2 Catalog SYSTEM SERVICES Perform logging Manage Log Inventory Manage Threads CICS Subsystem .

When an active log data set becomes full (or on operator command ). retrieval and update of database data. The functions of the individual components are as follows: PRECOMPILER This component is a preprocessor for the host language. the IRLM does not really have anything to do with it. Information regarding the data sets themselves is recorded in the BOOT STRAP DATA SET (BSDS). . Despite the “IMS” in its name . • Managing the system log : The system log is a set of predefined disk data sets that are used to record information for recovering user and system data in the event of a failure.DB2 SYSTEM SERVICES: This component handles all system wide tasks including connections to other MVS subsystems. LOCKING SERVICES: Provided by an MVS subsystem called the IMS Resource Lock Manager (IRLM). performance and accounting information. the precompiler constructs a database request module which becomes the input to the bind component. • Gathering system wide statistics. Its function is to analyse the host language source module stripping out all the sql statements it finds and replaces them by the host language CALL statements.to implement the functions of the sql. • It also handles system startup and shut down operator communication. The necessary support is provided by a series of five sub components : • Precompile • Bind • Runtime Supervisor • Data Manager • Buffer Manager Together these components support the preparation of the application programs for execution and the subsequent execution of those programs. DB2 switches to a new data set and copies the old one to an archive log data set on disk or tape.13 - . It is a general purpose lock manager which controls the concurrent access to db2 data. they are recycled. DATABASE SERVICES: The primary purpose of the database component is to support the definition . From the sql it encounters. When the active data sets are full.

Source listing . which it stores away as a member of an MVS partitioned data set  DBRM contains a copy of the original SQL statements. PRECOMPILATION COBOL SOURCE MODULE P PRECOMPILER . The precompiler searches for sql statements embedded in EXEC SQL and ENDEXEC.14 - .Diagnostics .DB2 THE PROCESS: • • • • • • Searches for and expands DB2 related include members . etc. Searches for sql statement in the body of the programs source code . . replaces each original sql statement. CALL Long-Interface Modified COBOL Source Module P.DBRM for P (SQL statements. together with additional information .Cross-References etc. Reports on the success or failure of the precompile process. Creates a modified version of the source program in which every sql statement in the program is commented out and a call to the db2 runtime interface module along with applicable parameters .)  It uses the SQL statements to build a DBRM for P. Extracts all sql statements from the program and places them in a dbrm to ensure that these two items are inextricably tied.

The output of the bind plan is an application plan containing executable logic representing optimized access paths to DB2 data. BIND PLAN vs BIND PACKAGE: In some cases however. the packages may be bound into a plan. then all relevant plans had to be recompiled and rebound in their entirety. The package concept was introduced to remedy these deficiencies.DB2 BIND: This component is the compiler for the sql statements. Before u can run a DB2 program. Adding a new DBRM to an existing plan required (again) a recompilation and rebind of the entire plan. if that DBRM ever needed to be recompiled . It reads the sql statements from the DBRM’S and produces a mechanism to access data as directed by the sql statements being bound. that same DBRM had to be compiled multiple times –and . Instead it may first be bound into a package and then finally. an application plan name must be specified. An application plan is executable only with a corresponding module. Indeed.the entire plan had to be recompiled and rebound. bind and rebind times are becoming unacceptably high in some DB2 installations and availability was suffering as a result. it may not be necessary to do a new plan bind to incorporate the new package either. If a given DBRM needs to be recompiled. all that has to be done is an appropriate package bind –it is not necessary to recompile the entire plan. regardless of the environment. a DBRM may not be bound directly into a plan. . There are certain disadvantages of directly binding the DBRM’s into an application plan : • • • • If an individual DBRM needed to be recompiled for any reason(for eg some index was dropped). Partly as a consequence of the foregoing points.15 - . If multiple plans involved the same DBRM . The major functions of bind are : • Parsing and syntax checking • Optimization • Authorization • Check that DB2 tables and columns being accessed conform to the corresponding DB2 catalog information. The bind plan accepts as input one or more DBRM’s produces from the previous DB2 program precompilation.

DB2 Application Programs Preparation & Execution :(Control Flow Diagram Overview) Source Module Modified Source Module Compiler (Load Module) application plan Runtime Supervisor Data Manager Load Module Buffer Manager Precompiler DBRM BIND Object Module Linkage Editor Appln. It employs sophisticated techniques to get the best performance out of the buffer pools under its care and to minimize the amount of physical I/O actually performed. Plan DB . logging. the data manager is the component that manages the physical database(s). update . DATA MANAGER: The data manager can be thought of as a very sofisticated access method. which uses control information in the application plan to request the appropriate operations on part of the data manager.16 - . I/O operations etc during the performance of its basic task. BUFFER MANAGER: The buffer manager is the component responsible for physically transferring data between external storage and virtual memory. retrieval. index maintenance etc. It performs all of the normal access method functioning such as search. It invokes other system components as necessary in order to perform detailed functions such as locking.DB2 RUNTIME SUPERVISOR: The runtime supervisor is resident in main memory when the application program is executing. When the application program requests some database operation to be performed (wishes to execute some sql). Its job is to oversee that execution. Broadly speaking. control first goes to the runtime supervisor.


there is also an associated format for writing literals of that type. DB2 DATATYPES DATA TYPE DESCRIPTION VALURANGE STORAGE REQUIRED INTEGER Full word binary integer SMALL INT Half word binary integer DECIMAL(p.the object appearing at the intersection of a given row and a given column of a given table.2 billion 1-32767 0<P<16 0<Q<P 4 bytes 2 bytes packed decimal format 8 bytes upto 254 bytes 5. Scalar objects can be operated upon by means of certain scalar operators.DB2 INTRODUCTION: The basic data object is the scalar value .18 - .79 to 7. DB2 also provides certain scalar functions which can be regarded as scalar operators.q) p-total no. Scalar objects and operators can be combined to form scalar expressions. For each such data type.2E + 75 0<n<255 . Each scalar value is of some scalar data type. of digits q .4E .digits to right of decimal point FLOAT long floating point CHARACTER(n) Fixed length string 1 .

19 - .59 SECONDS 0 .12 Day 1-n HOUR 0 .59 Seven Part value contains Data. TIME and Microseconds YYYY mmddnhmmssnnnnnn 3 bytes 10 bytes .DB2 DB2 DATATYPES DATA TYPE VARCHAR(n) string GRAPHIC(n) DESCRIPTION Variable length STORAGE REQUIRED 0<n4097 RANGE VALUE upto 4096 upto 254 bytes 4 bytes DATE TIME TIMESTAMP Fixed length 0<n<123 string of exactly n 16-bit character Year 0001-9999 Month 1 .24 MINUTES 0 .

’ ‘PIGON’ X ‘FIF2F3F40D156247’ : Written as a string of double byte characters preceded by the character ‘<‘ and followed by ‘>‘ the whole enclosed in single quotes and preceded by letter G. followed by a character E.0007 : Written as a decimal constant.5 07E1 Eg Character string Eg Graphic: string Eg : Written either as a string of characters enclosed in a single quotes or a string of pairs hexadecimal digits enclosed in single quotes preceded by letter X.DB2 CONSTANTS & LITERALS Integer Eg Decimal Eg Float : Signed or unsigned decimal integer with no decimal point : 4 -15 +364 0 : Signed or unsigned decimal number with decimal point : 40 -95.05 0.7 +364. : G ‘<STRING>‘ . : ‘123MAIN St. followed by an integer constant : 4E3 -95.20 - .7E46 +364E.

LENGTH: Computes the length of the scalar value in bytes .g.3) would extracts ‘AAR’ TIME: Converts a scalar value to time. HEX: Converts a scalar value to a character string representing a internal HEX code HOUR: Extracts the hours portion of a time or timestamp. SECOND: Extracts the second portion of a date or timestamp. FLOAT: Converts a number to a floating point representation. Assume = ‘AARTI’ e.DB2 NUMERIC OPERATORS: ARE +. INTEGER: Converts a number to integer representation. • . SUBSTR: Extracts a part of the string from a string. DATE: Converts a scalar value to a date.1. time .g (INITIALS || LASTNAME) CHAR: Converts a date. MINUTE: Extracts the minute portion of a date or timestamp.*./ FUNCTIONS: • • • • • • • • • • • • • • • • CONCATENATION ( ): can be used to concatenate two character strings or two graphic strings. SUBSTR(SNAME. DAYS: Converts a date or timestamp to a number of days.-. DAY: Extracts the day portion of a date or a timestamp. DIGITS: Converts a number(decimal or integer) to a character string representation.21 - . E. MICROSECOND: Extracts the microsecond portion of a timestamp. DECIMAL: Converts a number to decimal representation.timestamp to its character string representation.

SPECIAL REGISTERS Each individual user is assigned an authorization ID.’(w):’|| workph.value(‘(H):’||homeph. Once signed on. users can operate under their primary id or using the sql statement (SET CURRENT SQLID) they can switch to a secondary id.fname.g. users sign on to the system under their primary id. and serves as the primary id for the user in question. That id is used to sign on to the system. ’no phone’) VARGRAPHIC: Converts a character sting to a graphic string.) to a timestamp VALUE: Converts a null value into a non null value. . Each functional area(eg each department) in the organization is also assigned an authorization id. that id is typically not given the sign-on authority. YEAR: Extracts the year portion of a date or timestamp. A given primary id can have any number of secondary ids also that the same secondary id can be used by any number of primary ids. Select custno.DB2 • • • • TIMESTAMP: Converts either (a) Single scalar value or (b) a pair of scalar values (representing a date and time resp. However. e. Tables and other objects that are purely private to that user will typically be created under the control of.lname. An external subsystem such as IBM’s RACF keeps track of the secondary id(s) that can legitimately be used by a given primary id.22 - . and hence be owned by the primary id.

DB2 SCALAR EXPRESSIONS Six types of scalar expression are • Numeric • Character String • Graphic String • Date • Time • Timestamp expressions Assignments : Assignment operations are performed when values are retrieved from the DataBase or stored into the DataBase.23 - . Comparisons : The general form of a comparison is • Comparand operator comparand where  Two comparands must be compatible  The operator is any of the following > .CURRENT DATE SUM (QTY) =500 . ~= Examples WEIGHT * 454=1000 SUBSTR (PNAME.1) = ‘C’ FINAL_DATE = REVIEW DATE .1.>= .<= . <. = .

it has a weight but (c) we do not know what that weight is.that is stored as a prefix to the actual data column. but that it is nevertheless still legal to omit a value for the column on insert. In DB2. DB2 will automatically place a null in that position. Instead we mark that slot as null. and a row is inserted into the table and no value is provided for that column. NOT NULL WITH DEFAULT means that the column in question cannot contain NULLS. If a row is inserted and no value is provided for some column on which not null with default applies. In general any column can contain nulls unless the definition of that column explicitly specifies NOT NULL.24 - . we might say loosely that the weight of some part is null. meeting agenda’s often show a speaker as “to be announced” and police records may have entries as “present whereabouts not known”.DB2 NULLS : Means missing information. Hence it is desirable to have some way of dealing with such situations in our formal database systems. For example .DB2 automatically places one of the following default values in that position: • Zero for numeric columns • Blanks for fixed length columns • Empty (zero-length string) for varying length string columns. historical records sometimes include such entries as “date of birth not known:. The problem with missing information is that is frequently encountered in the real world. For e.g. If a given column is allowed to contain nulls. SQL systems like DB2 represent missing information by means of special markers called NULLS. . a column that can accept nulls is physically represented in the stored database by two columns.one byte wide . What we mean by such a statement is that (a) the part exists (b) of course . the data column itself and a hidden indicator column .


There are various differences of detail between a given interactive SQL statement and its corresponding embedded form. • • • • • Embedded SQL statements are prefixed by EXEC SQL and are terminated by ENDEXEC SQL statements can include references to host variables Any tables (base tables or views) used in the program must be declared After any SQL statement has been executed.26 - .DB2 EMBEDDED SQL: Any SQL statement that can be used at the terminal can also be used in an application program. feedback information is returned to the program in an area called the SQL Communication Area (SQLCA) The embedded SQL SELECT statement requires an INTO clause specifying the host variables. .


Host variables can appear in SQL data manipulation statements. END-EXEC SQL statements can include references to host variables. :city from employee where sno = :given-sno. such references are prefixed with a colon to distinguish them from SQL column names . They are generally used for designating a target for retrieval.DB2 HOST VARIABLES: Host variables are variables declared in the working storage section and are used by DB2 when it moves data between your program and a table. city into :status .28 - . They are defined according to the rules of programming language. Such variables can appear in the following positions : • Into clause in select or fetch (target for retrieval) • Where or having clause (value to be compared) • Set clause in update (value to be assigned) • Values clause in insert (value to be inserted) Example EXEC SQL Select status .


then it may be used for a list of columns with the first occurrence of the indicator variable corresponding to the first column in that list using a single indicator variable.30 - .:PCOLOR:COLOR-IND. • • • • • Each indicator variable is a half-word integer (pic S9(4) comp). indicates that the column has been set to Null  The value 2 indicates that the column has been set to Null as a result of Data Conversion Error  A positive or a zero value indicates that the column is not Null . CITY) VALUES (:PNO. it indicates a truncated variable is the length of the character string before truncation If the Indicator variables contain :  A negative No. Nulls can be handled for all the fields of the table. If the indicator variable returns a value > 0. From s Where sno = :Given-Sno END-EXEC. a check can be performed as : IF STATUS-IND < 0 THEN /*STATUS WAS NULL */ • Indicator variables can be used in the VALUES clause to insert NULL VALUES. The indicator variable will have a negative value if the select returns a null value. the user should include an INDICATOR VARIABLE in the into clause in addition to the target variable as illustrated in the following example: EXAMPLE : • EXEC SQL Select status .COLOR. EXAMPLE: IF COLORIND < 0 OR CITYIND < 0 EXEC SQL INSERT INTO P (PNO. :PCITY:CITYIND) END-EXEC.DB2 INDICATOR VARIABLE In general if there is a chance that the source or a retrieval operation might be null. Into :status:status-ind. city :city:cityind For processing and finding out whether the fields were NULL or not. If defined as an array (occurs clause) .

DNAME.is truncated on retrieval because the host variable is not large enough. MGR. LOC INTO :DCLDEPT: DEPT-IND FROM DEPT WHERE DEPTNO = ‘A00’ END-EXEC Indicator variables can appear on the right hand side of an assignment in the SET clause to set a value to NULL.DB2 • If a column. HO. EXEC SQL SELECT DEPTNO. the indicator Variable.31 - . contains the original length of the truncated column EXAMPLE: 01 DEPT-INDICATORS. 10 DEPT-IND OCCURS 5 TIMES PIC S9(4) COMP. defined as a char data type. . • EXAMPLE: IF RANKIND = < 0 EXEC SQL UPDATE S SET STATUS = :STATUS:STATUS-IND WHERE CITY =’LONDON’ END-EXEC.



34 - .DB2 CURSORS .

Declaring a Cursor EXEC SQL DECLARE cursor CURSOR FOR SELECT col1. Therefore no information is being retrieved from the database yet. END-EXEC. The Cursor name should begin with a letter and must not exceed 18 characters. col2.. one at a time to be executed in a loop • Close cursor : to close the cursor Declaring (defining) a cursor is done in the data division of your program.. When the open statement is encountered the select in the cursor declaration is executed. This is purely declarative in nature..35 - . . FROM table WHERE condition [FOR UPDATE OF col1. The open cursor statement not only executes the selection of data from the DB2 database but also establishes the initial position of the cursor in the results table. The cursor facility allows a COBOL program to gain addressability to individual row occurrences of a manyrows result table Following steps to be performed to use cursors • Declare cursor : to define cursor • Open cursor : to create result table • Fetch cursor : to retrieve rows from cursor. col2 .... Closing a cursor : EXEC SQL CLOSE cursor END-EXEC.DB2 CURSORS: A mechanism allowing an application program to retrieve a set of rows. :host var2. One program can have multiple cursors.] END-EXEC Opening a Cursor EXEC SQL OPEN cursor END-EXEC Fetching a row from cursor : EXEC SQL FETCH cursor INTO : host var1..


37 - . . These statements are similar to select statements which operate on a set of data at any given point of time. order by or built-in functions Only those columns are eligible for updation which are selected in the for. The cursor is declared with a special FOR UPDATE OF CLAUSE. EXEC SQL DELETE FROM table WHERE CURRENT OF cursor END-EXEC.. A for update of clause appears with: • • • Select statement to indicate what columns can be updated when retrieved The columns to be updated must be listed in the for update of clause or the declare You do not have to select a column to update it Rules for Update • • • • The select statement must be on a single table and not on a join If the declare cursor statement contains a subquery it must not be on the same table as the main query You cannot use distinct. field = : exp] WHERE CURRENT OF cursor END-EXEC. update clause The current forms of UPDATE & DELETE EXEC SQL UPDATE table SET field = : exp [. either update or delete data.DB2 DATA MODIFICATION: Often an application program must read data and then based on its value. group by. This is accomplished with a cursor and a special clause of the update and delet statements usable only by embedded SQL namely :WHERE CURRENT OF. One can use the UPDATE or DELETE SQL statements to modify and delete rows from DB2 tables.

EXEC SQL CLOSE C1 END-EXEC. If sqlcode < 0 GO TO 9999-error-paragraph.38 - . Mgrno From Dept Where ADMRDEPT = :ADMRDEPT for update of MGRNO END-EXEC. MOVE ‘A00’ TO ADMRDEPT. PROCEDURE DIVISION. : mgrno END-EXEC. EXEC SQL OPEN C1 END-EXEC. PERFORM 200-MODIFY-DEPT-INFO UNTIL NO-MORE-ROWS. . : deptname. Deptname.DB2 Example: (Use of Cursor) EXEC SQL Declare C1 cursor for Select Deptno. 200-Modify-Dept-Info. EXEC SQL Fetch C1 into :deptno. If sqlcode = +100 Move ‘NO’ to more-rows Else EXEC SQL Update Dept Set MGRNO = ‘00000’ Where current of C1 END-EXEC.

Move deptno to HV-WORKDEPT EXEC SQL Open Empcur END-EXEC. using cursors: EXEC SQL Declare Deptcur cursor for Select Deptno. salary from emp where workdept = :hv-workdept END-EXEC. Deptname From Dept END-EXEC. EXEC SQL Open Deptcur END-EXEC. Process retrieved data End Loop (2) End of Loop (1) .39 - . Loop until no more employee rows or error EXEC SQL Fetch empcur into :empno. EXEC SQL Declare Empcur cursor for Select empno.DB2 DATA RETRIEVAL Pseudocode for retrieving data from an application join . :Deptname END-EXEC. Loop until no more dept rows or error EXEC SQL Fetch deptcur into :Deptno . :salary END-EXEC.

we implicitly close the cursor. leaves it open.however is that every time we issue a commit. If the cursor declaration specifies with hold.000 transactions. a table of one million rows might be processed by a sequence of 10. This way . for e. each one dealing with just 100 rows. then at most 100 updates will have to be undone. However it is important to note that the first operation on the cursor following the commit must be fetch. e. commit does not close the cursor. The first thing each transaction has to do. thereby losing our position within the table. positioned such that the next FETCH will move it to the next row in sequence. The significance can be understood by considering what happens in its absence. one row at a time by means of a curso and update a few of the as we go.g. It is often desirable to divide the work up into batches and to make the processing of each batch into a separate transaction (by issuing a separate commit at the end of each one).40 - . The problem with this approach . And that re-positioning code can often be quite complex. Update and delete current are illegal. instead. thus. if it becomes necessary to roll a given transaction back. however.g. Suppose we need to process some large table. therefore is to execute some re-positioning code in order to get back to the row that is due to be processed next. especially if the processing sequence is determined by a combination of several columns. The possibly complex code for repositioning is thus no longer required.DB2 WITH HOLD OPTION: This is an optional specification on a cursor declaration. . instead of potentially as many as a million.


Example using ‘WHENEVER’ 1000-INQUIRY. 1000-EXIT. and use all specific error checking after each SQL statement is issued.DB2 WHENEVER: The whenever statement has the syntax : EXEC SQL WHENEVER condition action END-EXEC.There is no limit to the no. The whenever statement causes the program to automatically check the sqlcode. Some application programmers prefer (for structured reasons) to avoid the whenever statement. . EXIT. EXEC SQL WHENEVER SQLERROR GOTO 1000-UNDO END-EXEC. of whenever statements you can use. it takes the action you specify. the default of continue will apply for that condition. EXEC SQL SELECT FLD1. FLD2 INTO : FLD1. :FLD2 FROM EMP-TABLE WHERE CODE = 113 END-EXEC. Where “condition” is one of the following : NOT FOUND means SQLCODE = 100 SQLWARNING means SQLCODE >0 & NOT = 100 SQLERROR means SQLCODE < 0 “ACTION ” specifies a CONTINUE or a GO TO statement. 1000-UNDO DISPLAY ‘ERROR! CAN’T PROCEED’ EXEC SQL ROLLBACK END-EXEC.42 - . Based on the value it finds. If you omit the action for a whenever statement.


that transforms a consistent state of the database into another consistent state.1000) END-EXEC. UNDO: EXEC SQL ROLLBACK END-EXEC FINISH: RETURN The insert adds the new shipment to the sp table. the intent of which is to add a new shipment (S5. without necessarily preserving consistency at all intermediate points. in general. Now consider the following sequence of operations. Suppose for the sake of example the parts table contains an additional column totqty representing the total quantity for the part in question.44 - . rather it is a sequence of several such operations. Thus a logical unit of work is not necessarily just one SQL operation . the update updates the totqty column for the part p1 appropriately. Now it is clear that what must not be allowed to happen in the example is for one of the . Consider the following example. What is more is that the database is not consistent even between thise two updates.qty values taken all over sp rows for that part.P1. EXEC SQL INSERT INTO SP VALUES (‘S5’.1000) to the database: EXEC SQL WHENEVER SQLERROR GOTO UNDO END-EXEC.’P1’. The value of the totqty for any part is supposed to be equal to the sum of all sp. The point of example is that what is presumably intended to be a single atomic transaction “create a new shipment” –infact involves 2 updates to the database.DB2 WHAT IS A TRANSACTION ? A transaction is a logical unit of work. EXEC SQL UPDATE P SET TOTQTY = TOTQTY + 1000 WHERE P# = ‘P1’ END-EXEC EXEC SQL COMMIT WORK END-EXEC.

signals unsuccessful end-of-transaction indicating an inconsistent state and all the updates made by the logical unit of work must be rolled back or undone.DB2 two updates to executed and the other not (because then the database would be in an inconsistent state). Ideally we would want that both the updates are done. For example a system crash may occur between the two updates. But a system that supports transaction processing does provide the next best thing to such a guarantee. but we cannot have such a guarantee: there is always a chance that things will go wrong. The system component that provides this atomicity is know as the transaction manager and the COMMIT WORK and ROLLBACK WORK are the keys to the way it works. it guarantees that if the transaction executes some updates and then a failure occurs. the those updates will be undone. for whatever reason before the transaction reaches its normal termination. The COMMIT WORK operation signals successful end-of-transaction :it tells that transaction manager that a logical unit of work has been successfully completed. SYNTAX: COMMIT The SQL commit statement takes the form EXEC SQL COMMIT [WORK] END-EXEC. Thus the transaction either executes in its entirety or is totally cancelled. ROLLBACK The SQL ROLLBACK statement takes the form EXEC SQL ROLLBACK [WORK] END-EXEC . The ROLLBACK operation by constrast. Specifically.45 - .


transaction A updates the row(on the basis of the values seen at time t1) at time t3.DB2 THREE CONCURRENCY PROBLEMS: DB2 is a shared system. They are • The lost update problem • The uncommited dependency problem • The incorrect analysis problem The lost update problem: Consider the situation as shown in the figure: The Lost Update Problem TRANSACTION A FETCH R UPDATE R T4 T3 T2 T1 TIME TRANSACTION B FETCH R UPDATE R - Transaction A retrieves some row R at time t1 . There are essentially three ways in which things can go wrong. Transaction A’s update is lost at time t4. which are the same as seen at time t1) at time t4. it is a system that allows any number of transactions to access the same database at the same time. transaction B retrieves the same row at time t2.three ways. becauses transaction B overwrites it without even looking at it. . and transaction B updates the same row (on the basis of the value seen at time t2. Any such system requires some kind of concurrency control mechanism to ensure that current transactions do not interfere with each others operation and DB2 includes such a mechanism namely locking. i.e.47 - .

DB2 The uncommitted dependency problem: This problem arises if one transaction is allowed to retrieve (or update) a row that has been updated by another transaction and has not yet been committed by that other transaction. there is always a possibility that it never will be committed but will be rolled back instead. For if it has not been committed. where as in fact .in which case the first transaction will have data that now no longer exists. Transaction A is therefore operating on false assumption that row R has the value as seen at time t2.48 - . transaction A sees an uncommitted update at time t2. Inconsistent analysis problem: This problem could be a simple summation problem. As a result. That update is then undone at time t3. . transaction A may well produce incorrect output. it has whatever value it had prior to time t1. Consider the figure given below: The Uncommitted Dependency Problem TRANSACTION A T1 FETCH R T3 T2 ROLLBACK TIME UPDATE R TRANSACTION B TRAN A BECOMES DEPENDENT ON AN UNCOMMITTED CHANGE AT TIME T2 In this example .

will not change in some unpredictable manner while its back is turned . B will wait until A’s lock is released.DB2 How DB2 solves these problems: DB2’s concurrency control mechanism is based on a technique called locking. it “times out” and the lock request fails ( a negative SQLCODE is returned) CO PATIBILITY M M ATRIX A B X S X N N S N Y From the compatibility matrix . A request from transaction B for an S lock on R will be granted (that is . two inferences can be drawn: If transaction A holds an X lock on row R . the installation can specify a maximum wait time . it acquires a lock on that object and there by to prevent them from changing it. then a request from transaction B for a lock of either type on R will cause B to go into a wait state. the transaction simply waits until it is. If transaction A hold a shared lock (S) lock on row R . B will now also hold an S lock on R) . In practice. then if any transaction ever reaches this threshold in waiting for a lock. We assume that if a transaction requests a lock that is currently not available . The first transaction is thus able to carry out its processing in the certain knowledge that the object in question will remain in stable state for as long as that transaction wishes it to The two types of locks that can be placed are shared lock(S) and exclusive lock (X).49 - . then A request from transaction B for an X lock on R will cause B to go into a wait state (and B will wait until A’s lock is released). The basic idea of locking is simple: when a transaction needs and assurance that some of the object it is interested in typically a database row .

as it will in FETCH/UPDATE or FETCH/DELETE SEQUENCE.50 - . then the update or delete “promotes the S lock to X level. As one can see. transaction A’s update at time t3 is not accepted because it is an implicit request for an X lock on R. it automatically acquires an S lock on that row. . discussed later. so A goes into a wait state. When a transaction successfully fetches a row . B goes into a wait state at time t4. For analogous reasons . it automatically acquires and X lock on that row. If it already holds an S lock on that row. Now both transaction are unable to proceed. This problem is called the deadlock problem. and such a request conflicts with the S lock already held by transaction B. The lost update problem revisited Handling the Lost Update Problem TRAN A FETCH R (acquires S lock on R) UPDATE R (request X lock on R) Wait Wait T4 Wait Wait UPDATE R (request for X lock on R) TIME TRAN B FETCH R (acquires S lock On R) - T1 T2 T3 The above figure shows what would happen to the interleaved execution under the locking mechanism of DB2.DB2 Transaction requests for row locks are always implicit.DB2 thus solves the lost update problem by reducing it to another problem but at least it does solve the original problem. When a transaction successfully updates a row. so there is no question of any update being lost.

so A goes into a wait state and remains so until B reaches a synchpoint(either commit or rollback). because it is an implicit request for a lock on R. Either way. when B’s lock is released and A is able to proceed. and such a request conflicts with the X lock already held by B.DB2 The uncommitted dependency problem revisited Handling the Uncommitted Dependency Problem TRAN A FETCH R (request for S lock on R) Wait ` Wait T3 Wait resume : FETCH R (X lock on R)` T4 TIME TRAN B UPDATE R (X lock on R) SYNCPOINT (Release X lock on R) T1 T2 Transaction A’s operation at time t2 is not accepted . . if B terminates and with a ROLLBACK .51 - . A is no longer dependent on an uncommitted update. or the post – b value otherwise. and at that point A sees a committed value (either the pre – B value.

each query must modify the other index so it would reflect the new. The chance that a page needed by program A will already be held by program B is thereby reduced. This technique locks with INTENT UPDATE. after the data is reached by means of one index. Both programs should access various tables in the same sequence. However.. for the same reason. The problem with such updates can be exemplified as follows: User A is updating page 1 using index X for access to the data. • Avoid clashing updates through different paths (if possible). • Multi-row updates and deletes. User B is updating page 2 using index Y for access to the data. This is a more relaxed lock than an exclusive lock. . Both programs should advance along the tables in ascending key order. Such deadlocks are hard to avoid. Thus. but it still prevents other programs from locking one of your pages exclusively. that other index is still locked by the other query. A 'deadlock' occurs when program A locks page X exclusively and attempts to lock page Y. Therefore. you can: • Use the same sequence of update. Neither program can continue without the required lock.. You may watch out for some conditions which make this situation more likely: • Large number of indexes on a table. Use cursor with FOR UPDATE OF . To avoid this situation. ahead of time. • Large value used for SUBPAGES for the index. Index X references data on page 2 and index Y references data on page 1).DB2 Deadlocks . with frequent deletes or updates.52 - . updated data.e. and after that data is updated. fewer deadlocks and fewer time outs will occur. while program B has already locked page Y exclusively and attempts to lock page X. • Use frequent COMMITs. each index also references the data on the other page (i. However. DB2 cancels one of the processes (the one with the fewest log records) with a time out code. all the pages which you will need. this makes it less likely that they will cross each other's paths and attempt to lock the same page.. less contention.

DB2 provides certain explicit facilities which the programmer should be aware of.53 - . this command either locks up the table or an entire table space SYNTAX LOCK TABLE table IN mode MODE Where “mode” is SHARE or EXCLUSIVE & “table” must designate a base table not a view. This results in saving of system resources. Once a lock is acquired no other transaction will be able to access any part of the table in any way .until the original lock is released. The explicit facilities consists of : the SQL statement LOCK TABLE . . The Lock table statement can be used to control locks from within a DB2 application program. When that original lock is released depends on the RELEASE parameter on BIND. Every individual page lock uses system resources in storage and processing time A single table lock reduces the storage and processing time required by the many small locks. LOCK TABLE : Depending on the versions. the table space LOCKSIZE parameter and the ACQUIRE/RELEASE PARAMETER on the bind plan.DB2 Explicit locking facilities In addition to the implicit locking mechanism described earlier. the ISOLATION PARAMETER on the bind plan command.

DB2 supports two isolation levels for every transaction • Cursor Stability (CS) • Repeatable Read (RR) These are used while cursor manipulation Cursor Stability DB2 takes a lock on the page the cursor is accessing and releases the lock on that page.DB2 ISOLATION PARAMETER: Specifies the isolation level for the application plan being bound. In repeatable read. . By contrast. when the cursor moves onto a different page (This is not done when we use FOR UPDATE of statement in cursor) The lock on the last page is released at commit time (or at Thread de-allocation time) Repeatable Read In cursor stability. The problem with CS is that a transaction operating at that level may have a record changed “behind its back” as in inconsistent analysis problem and so may produce a wrong answer. while your transaction reads data.54 - . Cursor Stability provides more /higher concurrency while repeatable read provide more consistency. other transaction could change the data you have already read. a transaction that operates under isolation level RR. can behave completely as if it were executing in a single user system. DB2 holds all page locks while the cursor is moving all till the transaction commits (or till thread deallocation).

of pages that are locked exceeds an installation default. ANY : (Which is the default) means that DB2 itself will decide the appropriate physical unit of locking for the tablespace for each plan .DB2 LOCKSIZE PARAMETER: Physically. TABLE. • • • • TABLESPACE : means all locks acquired on data in the tablespace will be at the tablespace level TABLE : means locks acquired on data in the tablespace will be at the table level PAGE : means locks acquired on data in the tablespace will be at the page level whenever possible. For a given table space.55 - . depending on what was specified as the LOCKSIZE for the relevant table space in the CREATE or ALTER TABLESPACE operation. the LOCKSIZE can be specified as PAGE. TABLE SPACE or ANY. DB2 locks data in terms of pages or tables or table spaces. . but if the no. DB2 does a lock escalation and automatically locks a larger unit.Defaults to a page lock.

they are • COMMIT & DEALLOCATE While Binding.This option tells DB2 to release all locks only when the program ends (i. DB2 allows us to specify transaction level lock acquiring and releasing parameters. use ACQUIRE (ALLOCATE) and RELEASE (DEALLOCATE). RELEASE: Similar to the DB2 acquire parameters. For ACQUIRE.DB2 ACQUIRE/RELEASE PARAMETERS DB2 always implicitly acquires locks of some kind The acquire and release parameters on the BIND command specify when such tablespace level locks are to be acquired and released . ACQUIRE (allocate) . Release (de-allocate) . RELEASE (commit) . the possible specifications are • USE & ALLOCATE.56 - .This option tells DB2 to release all locks of transaction commit time. the thread is de-allocated). For better performance. there are 2 release parameters. This is DB2 default. ACQUIRE: ACQUIRE (use) . . • • • All combinations except ACQUIRE (Allocate) and RELEASE (commit) are allowed.e. For RELEASE.This option tells DB2 to take locks at the time of SQL statements execution.This option tells DB2 to take all necessary locks at the start of the transaction. This is the DB2 default. use ACQUIRE (use) and RELEASE (commit). For more concurrency. This is the DB2 default.


DB2 The DB2 INTERACTIVE INTERFACE (DB2I): This interface provides following: • • • • • Ability to execute SQL statements interactively To invoke prewritten application programs Ability to issue operator commands Ability to invoke database utilities Ability to produce application programs for execution. select DB2I. The DB2I main menu will offer following options. From ISPF menu.58 - . INVOKING (DB2I) • •         Log on to TSO and enter ISPF. SPUFI DCLGEN PROGRAM PREPARATION PRECOMPILE BIND/REBIND/FREE RUN DB2 COMMANDS UTILITIES .

3278 D1 DB2T -DB2 Test Options D2 DB2P -DB2 Production Options E EXPEDITER -Debugging Tool F FILE-AID -Editor and Utilities FA File Age -Platinum Trans Century File Age (2.0.Datacenter Functions ---------------------------OPTION ===> D1 Type an option and press Enter.DB2 SPUFI • • Supports the interactive execution of SQL statements from a TSO terminal You can create a text file containing one or more SQL statements (using the ISPF editor).01:18 C CA-7 -CA-7 Production Scheduler TERMINAL .DA0021T A ACF2 -ACF2 Access Control Facility TIME .3) H DF/HSM -Hierarchical Storage Manager IN INFORM -Display Mega Center Information IS ISMF -Interactive Storage Management Facility J JCLWTR -Sysout Archiver JS JOB/SCAN -Job/Scan utilities L LIBRARIAN -Program source manager N NDM -Data Transfer Utility (for messages only.0 XC XCOM 6.2 -Multi platform file transfer application . USERID .59 - . • • • • • • • • • • • • • • • • • • • • • • ---------------------------. then execute that file via SPUFI. and then use “ISP Browse” to browse through the results of these statements (which will have been written to another text file). Intended primarily for application programmers who wish to test the SQL portions of their programs. type NM) R RMDS -Report Distribution and Viewing ST STROBE -STROBE Monitoring Facility V VPS70 -Printer Control Facility 7.

3 lp (Process SQL statements) (Generate SQL and source language declarations) (Prepare a DB2 application program to run) (Invoke DB2 precompiler) (BIND. or FREE plans or packages) (RUN an SQL program) (Issue DB2 commands) (Invoke DB2 utilities) (Set global parameters) (Leave DB2I) CRTLU004 02-016 A SB# .60 - . REBIND. 1 2 3 4 5 6 7 8 D X SPUFI DCLGEN PROGRAM PREPARATION PRECOMPILE BIND/REBIND/FREE RUN DB2 COMMANDS UTILITIES DB2I DEFAULTS EXIT LTTI 00:03.DB2 • • • • • • • • • • • • • • DB2I PRIMARY OPTION MENU COMMAND ===> 1 SSID: DST2 Select one of the following DB2 functions and press ENTER.

..61 - ...===> DA0021T... ===> YES (Y/N .4 lp CRTLU004 10-041 A .AARTI.………..===> DA0021T.OUT1 Specify processing options: 5 CHANGE DEFAULTS ===> NO (Y/N ..===> YES (Y/N ...Browse output data set?) For remote SQL processing: 10 CONNECT LOCATION ===> PRESS: ENTER to process END to exit HELP for more information SB# LTTI 00:03.Enter SQL statements?) 7 EXECUTE .DB2 SPUFI SSID: DST2 • ===> • • • • • • • • • • • • • • • • Enter the input data set name: (Can be sequential or partitioned) 1 DATA SET NAME . ….. ===> YES (Y/N . ===> (Enter if not cataloged) 3 DATA SET PASSWORD ===> (Enter if password protected) Enter the output data set name: (Must be a sequential data set) 4 DATA SET NAME ….Display SPUFI defaults panel?) 6 EDIT INPUT .. ===> YES (Y/N ...SQL(Q1) 2 VOLUME SERIAL ….. ....…….………..Execute SQL statements?) 8 AUTOCOMMIT ..Commit after successful run?) 9 BROWSE OUTPUT ..….

62 - .S L 1 .0 C lu n 0 0 1 0 0 2 o ms 0 0 0 7 C mn = = om a d = > S ll = = P G cro = > A E ****** **************************** T oD op f ata ************************************ 00 0 01 S L C * F O E P O E EE T R M ML Y E ****** *************************** B tto of D ta o m a ********************************* .A R I.0 0 D A 0 T A T Q (Q ) 1.DB2 • • • • • • • F E Cn ile dit o firm M n U e u tilitie C m ile T st H lp s o p rs e e ------------------------------------------------------------------------------E IT D 0 21 .

REBIND. 1 2 3 4 5 6 7 8 D X SPUFI DCLGEN PROGRAM PREPARATION PRECOMPILE BIND/REBIND/FREE RUN DB2 COMMANDS UTILITIES DB2I DEFAULTS EXIT LTTI 00:03.63 - . or FREE plans or packages) (RUN an SQL program) (Issue DB2 commands) (Invoke DB2 utilities) (Set global parameters) (Leave DB2I) CRTLU004 02-016 A SSID: DST2 SB# .3 lp (Process SQL statements) (Generate SQL and source language declarations) (Prepare a DB2 application program to run) (Invoke DB2 precompiler) (BIND.DB2 DCLGEN • • Allows the user to invoke the declarations generator program Program preparation :  precompilation  compilation or assembly  linkage editor processing  bind processing  program execution (TSO only) DCLGEN DB2I PRIMARY OPTION MENU • • • • • • • • • • • • • COMMAND ===> 2 Select one of the following DB2 functions and press ENTER.

..DB2SORCE(EMPDCL1)' 5 DATA SET PASSWORD ===> (If password protected) Enter options as desired: 6 ACTION ..===> YES (Enter YES for column label) 8 STRUCTURE NAME ... ===> NO (Enter YES to append column name) 12 INDICATOR VARS …... ===> 3 AT LOCATION ..……..………….AARTI. ===> (Optional) 9 FIELD NAME PREFIX. ===> YES (Enter YES to delimit DBCS identifiers) 11 COLUMN SUFFIX …..... ===> (Unqualified) (Optional) (Optional) Enter destination data set: (Can be sequential or partitioned) 4 DATA SET NAME …….DB2 • • • • • • • • • • • • • • • • • DCLGEN ===> SSID: DST2 Enter table name for which declarations are required: 1 SOURCE TABLE NAME ===> employee 2 TABLE OWNER ..……. ….. ===> REPLACE (ADD new or REPLACE old declaration) 7 COLUMN LABEL .. ===> NO (Enter YES for indicator variables) .……….. ===> 'DA0021T...===> (Optional) 10 DELIMIT DBCS ...64 - ....

DASD Manager and Catalog Manager) 5 DBEDIT -IBM's Data Base Edit Facility (DBEDIT) DBEDIT SSID ===> DST2 6 File-AID -Compuware's File-AID for DB2 Utility Request .DB2 v4.Query Management Facility QMF SSID ===> DST2 PRINT (YES/NO) ===> 4 DB2MM . Option I.Request Creation and Use of DB2 Objects Info Browse important information about the DB2 environment .DB2 Blue Testing Facilities Menu -----------------------OPTION ===> 4 1 DB2I 2 QMF .U Enter HELP for more information about the DB2 Facilities Menu Enter END Command to Exit the DB2 Facility Menu R I .New DB2 users should read the DB2 User Guide.DB2 Interactive .DB2 CATALOG MANAGER • • • • • • • • • • • • • • • • • --------------------.BMC's DB2 MasterMind Series of Products (DB2 Alter.09/14/97 .Check the HSM migration warning for DB2 datasets .65 - .1 information YOU need to know .

. .Manage or monitor DB2 physical objects 2 CATALOG MANAGER for DB2 .Execute DDL or query the DB2 Catalog 3 CHANGE MANAGER for DB2 . . . . . . .Manage changes to DB2 objects/structures • • DB2 SSID .DST2 DB2 Catalog Access . DIRECT (Direct) . .BMC Software Administrative Products for DB2----------------COMMAND ===> 2 1 DASD MANAGER for DB2 . .DB2 • • • • • ----------------. . . ……. .66 - . . . .

(O) CATALOG MANAGER options processing 5. TB Table 18. CI Collection Qualifier EMP% Initial attach to DST2 21.67 - .02 Primary Menu -------------------Command ===> Select action and type object information. DB Database 16. Action 0. DM DBRM . ST Strings 22. PL Plan 26. (C) Create objects 3. AL Alias 27. PR Procs 25. CK Checks 24. (Q) List SQL for edit & execution Obj typeTB 11.4. US User 28. SY Synonym 14. CO Column 29.-----------.DB2 • • • • • • • • • • • • • • • • • • • DST2. (M) Maintain logs menu 7. IX Index 20. (S) Search for catalog objects 2. SU SysPrivUser 13. TS Tablespace 12. (G) Grant privileges 4. SG Stogroup 17. Then press Enter. PG Package 15. (D) DB2 Commands 6. VW View 19.CATALOG MANAGER 5. LO Location 23. (L) List catalog objects (blank same as 0) 1.

EMPTAB DADB2 DATD2DB2 4 -1 -1 DA0021T.EMPTABLE DADB2 DATD2DB2 6 -1 -1 DA0021T. Type command and press ENTER Lst: AL CA CK CL CO DB DS FK IC IX KC MX PA PG PK PL RI SG SY TM TS TT UA US VW LIKE: EMP% C Table Name Database Tblspace Cols PK Rows Pages ----v----1----v----2----v----3----v----4----v----5----v----6----v----7----v-------------------------DA0021T.Row 1 of 32 Command ===> Scroll ===> PAGE 01 CMD will show commands for this list.EMP DADB2 DATD2DB2 1 -1 -1 DA0021T.EMP" DADB2 DATT2001 8 1 -1 -1 DA0021T."EMPL."EMPL.EMP1 DADB2 DATD2DB2 4 -1 -1 .EMPTABLE1 DADB2 DATD2DB2 5 -1 -1 DA0021T."EMPL.EMPLOYEE DADB2 DATD2DB2 9 1 -1 -1 DA0021T.Table List -------------------.PINF" DADB2 DATD2DB2 7 1 -1 PKDA0021T.DB2 DST2-R ------------------------.68 - .DEPT" DADB2 DATT2001 3 1 -1 -1 DA0021T.

Primary Key List -----------------.DB2 • • • • • • • • • • DST2-R ---------------------.EMPLOYEE Cmd Referenced Table/Column Constrnt R Dependent Table/Column ----v----1----v----2----v----3----v----4----v----5----v----6----v----7----v--DA0021T. Type command and press ENTER QUALIFIER: TABLE=DA0021T.EMPLOYEE EMPNO ******************************* Bottom of data ******************************** .Row 1 of 2 Command ===> Scroll ===> PAGE 02 CMD will show commands for this list.69 - .


71 - .This indicates a ‘W’ when an arithmetic operation produces an unusual date or timestamp .This is flagged if a value is truncated when assigned to a host variable SQLWARN2 .This flag is set to ‘W’ if a dynamic SQL update or delete statement does not have a ‘Where’ clause SQLWARN5 .Here a ‘W’ means you did not supply enough host variables in an into clause to match the columns in a select clause SQLWARN4 .This indicates that the SQL statement is valid only in SQL/DS and not in DB2 SQLWARN6 .This indicates that any of the following warnings are flagged.This is set to ‘W’ if some of the rows weren’t considered by a column function because the column being processed contained null values SQLWARN3 . SQLWARN1 .DB2 SQL WARNINGS SQLWARN0 .

Display ‘SQLERRD(3)’ ROWS WERE DELETED.  Eg. .DB2 SQL WARNINGS SQLERRD is an array of six full word items. contains useful information. EXEC SQL DELETE FROM EMP WHERE DNO IN (SELECT DNO FROM MASTER_DEPT) END-EXEC.The third of the six.72 - . sqlerrd(3) contains the no.delete or update statement.  After an insert. rows the statement affected.

SELECT. possibly because its name is not spelled correctly Duplicate keys not allowed DBRM not bound into this plan Embedded SELECT or sub select returned more than one row -803 -805 -811 Updating Plan SELECT .DB2 DB2 ERROR CODES SQLCODE +100 +304 -305 -501 -551 Keyword SELECT Program Variables Cursor Authority Meaning Row not found during FETCH. UPDATE or DELETE Value and host variable are incompatible Null value occurred. and no indicator variable was defined Cursor named in FETCH or CLOSE is not open You lack the authority to access the named object.73 - .

if resource name is a table view. permits running more SQL statements Unavailable resource. program was probably re-precompiled without being re-bound Mysterious system error.DB2 DB2 ERROR CODES SQLCODE -818 Keyword Plan Meaning Timestamps in load module and plan do not agree. etc. this was probably causes by contention and re-trying the operation maywork. updates rolled back Deadlock or timeout.74 - . the file has probably been archived or deleted -901 -904 System System -911 -913 System System Deadlock or timeout. updates not rolled back . if resource name is a 44 character VSAM file name.

75 - .DB2 Appendix –A ASSIGNMENTS .

Display the name and salary of the employee whose empno is as passed on as a host variable . Display the details of the highest paid employee. e) List all dept details from the DEPT table which has atleast one employee. b. Generate Table Declaration and host variable structure for above tables using the DB2I-DCLGEN option .INTEGER PRIMARY KEY . 2) -INTEGER FOREIGN KEY I. The dclgens should be stored in the same PDS where the source programs are.DECIMAL(6. III. d) List all employees hired during the year ‘82. g) List the minimum salary of various categories of employees department wise such that the salary is greater than 1500.CHAR (20) NOT NULL . i) List the names of all the clerks along with the name of their departments. II. Use SPUFI to execute the SQL statements a) List employees hired after 01/09/81 and working in the accounting dept. f) Count the total no. a NULL INDICATOR should be used to indicate the appropriate error message.76 - . j) Find the minimum salary of MANAGERS in various departments. Write a COBOL programs to : a. .VARCHAR(10) LOCATION . b) List the BIG BOSS of the company (who does not report to anyone).DATE . 2) .DB2 Consider the following tables : Table : EMPLOYEE EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO Table: DEPT DEPTNO .INTEGER . If the search returns a NULL value . of clerks. c) List all the employees whose names begin with N and the third character is J.DECIMAL(10. h) List the employees in the ascending order within each dept.INTEGER PRIMARY KEY DNAME .VARCHAR(10) .VARCHAR(10) .

t the salary)  if salary > 10000 and salary < =15000 grant him a commission of 20%  if salary > 15000 and salary <= 20000 grant him a commission of 15%  if salary > 20000 grant him a commission of 10% V. Increase the commission of employees. (The % increase is w. bind and execute the pgm using Jcls. 10. VI. . who have completed one year of service with following conditions. (Hint : commission can be null) Precompile. Compute and display the total salary of all the employees where the total salary is calculated as TSAL = SALARY + COMMISSION. Use a join to display the dept.r. linkedit. the location and the other employee details of all those employees who belong to department no. compile.77 - .DB2 IV. name. A additional commission of 10% of salary is granted to those employees who work as salesmen in the firm.

DB2 Appendix B .78 - .STANDARDS .

use odd precision i. • • • • • • • • . DISTINCT. “null” for foreign keys and “not null with default” for other colums.DB2 APPLICATION CONSIDERATIONS 1. SELECT …. PROGRAMMING CONSIDERATIONS: • Apart from enforcement of host language programming standards.79 - .2). 1.ORDER BY AND GROUP BY because they require DB2 to do an internal sort. DB2 holds the page locks and releases them at the next commit point.. Host variables must always have the same format as the corresponding table fields.2) instead of DEC(6. when used. When binding DB2 programs. When table definitions are altered.4 When using decimal fields.  Avoid too many joins or subqueries. Use BETWEEN instead of “>= & <=” Error checking  Every SQL statement execution is checked for the sql return code namely SQLCODE.UNION. select * will cause an abend.DB2 locks the current page only while in RR. cursor stability should be used instead of repeatable read because under cursor stability. some of the embedded SQL related programming practices are as follows:  Avoid the use of select * as this requires the program to have a variable for each column defined. However a join should be given preference over a subselect. place them at the end of the row as this would improve performance and at the same time allow the users the format they find the most convenient. 1. use DEC(7. Use select with a list of column names instead. Preferably use dclgen to copy the generated structure in the program. time may be spent unnecessarily to find out as to which of the underlying objects that were used in the plan that have been changed or dropped at the time of re-binding the plan. Restrict the use of SELECT.2 Avoid the use of the variable length columns unless there is a potential saving. Never code an arithmetic expression as an operand to be compare d to a column in a where clause because it degrades the performance of the sql statements.1 Keep the application plans small for easy maintenance otherwise. However . The check is made immediately after execution and the control is passed to the appropriate section of the code based on the return codes. Use validate (bind) instead of validate (run) because validate at run time can cause contention on the catalog tables because requiring more run time resources. Do not lock table unless approved by the DBA. 1.3 Use “not null” for primary keys.e.

to maximize concurrency. This can be controlled by increasing the sub-pages. The resources are acquired on use and released on commit. data should be stored over large number of pages.DB2 PERFORMANCE IMPROVEMENT GUIDELINES: • • • • • • • • Create more indexes. Index creation is always at the cost of the space and poor performance during inserts. Use validate(bind). This option is preferred to validate(run) since validate(run) would check for validity at bind time and re-check at run time for every run. This option keeps the resources for a shorter duration compared to the option acquire(allocate) / release(deallocate). Increase the sub-pages. . When locking is in effect.80 - . Use acquire(use)/release(commit) on bind. Reduce internal DB2 sorts. updates and deletes but access can be made faster by defining suitable indexes.

BIBLOGRAPHY .81 - .DB2 Appendix C .

DB2 Developers Guide : Craig Mullins . Date 2. A Guide to DB2 : C. IBM Database 2 General Information 5.DB2 BIBLIOGRAPHY 1. The DB2 Experts Guide : Bruce Larson 3.J. IBM DB2 Application Programming & SQL Guide 4.82 - .

Sign up to vote on this title
UsefulNot useful