You are on page 1of 28

DB2 Guide Page 1 of 28

DB2 Guide Page 2 of 28


DB2 is an abbreviation of IBM DATABASE II; it is Relational Data Base Management System (RDBMS) for
MVS operating system

In DB2, data is stored in the form of tables (relations) comprised of rows (records) and columns (fields). All
access to and manipulation of data in DB2 is accomplished via Structured Query Language (SQL).

DB2 objects

In MVS environment, the relational database manager itself (DB2) is considered a subsystem (an MVS
started task). Typically an installation consists of two or more subsystems. i.e, there is one for test and one
for production. For each DB2 subsystem, there are some system objects e.g. a catalog, a log, and a

DB2 Database
It is a logical grouping of tables, tablespaces and their indexes for management purposes. Normally, data for
a specific application is contained within one database

DB2 Tablespace

prepared and executed at runtime.DB2 Guide Page 3 of 28 Tablespace is physical collection of tables and their associated indexes. or select data from the database Data Manipulation Language objects statements grant or revoke privileges or authorities to perform Transaction Control Language database operations on the objects in your database . The data only exist in the base table only the definition of view is stored. Dynamic SQL In dynamic SQL the statements are constructed. Volume holds the datasets in which tablespaces and indexes are actually stored. updates. DB2 Index An Index is an ordered set of pointers to data in a DB2 table. Static SQL In static SQL the statement is prepared before execution. DB2 Storage Groups A DB2 storage group is a set of volumes on direct access storage devices (DASD). or deletes rows of the catalog tables that describe the object and also have the information how this object relates to other objects. Data Definition Language Statements create. DB2 tables DB2 tables holds data in the form of rows and columns. A Tablespace is divided into equal sized units (of 4k bytes). All SQL statements should be prepared (Bind) before they can be executed. alter. or drop database objects statements insert. When you create. An index space is automatically defined in the same database as the table. Tablespaces uses one or more VSAM linear datasets (LDS) and the maximum size of Tablespace is 64GB. A database can be stored in one or more storage groups. DB2 brings in the 4K page containing that byte. We can divide sql into three different categories. DB2 Catalog The DB2 catalog consists of a group of tables containing information about other objects with in the DB2 subsystem. Users have read access to these tables. update. DB2 inserts. In order to service a request to see one byte of data. Some of the tables in DB2 catalog are SYSTABLES Contains one row for each table. DB2 Views View is a virtual table defined on another table or view. delete. The result of preparation is executable form of statement (plan). view and alias SYSINDEXES Contains one row for each index SYSCOLUMNS Contains one row for each table and view SYSVIEWS Contains one row fro each view SYSRELS Contains one row for every referential constraint Structured Query language is a standardized language for defining and manipulating data. modify. or drop any object. called pages which are written to or read from DASD in one operation.

into a column whose data type is numeric. Similarly.DB2 Guide Page 4 of 28 DATA DEFINITION LANGUAGE Statements create. CREATE INDEX ix1 ON t1 (esal) ALTER TABLE emptab ADD date_of_joining DATE DROP VIEW view1 The data type of a column determines what you can and cannot do with the column. you cannot insert character data. For example.g. or drop database objects. e. When you perform operations on columns. like a last name. Index. To better understand the concepts that are presented in this section. string. Tablespace. you must understand the data types of the columns to which an example refers. the data must be compatible with the data type of the referenced column. Statements Available CREATE ALTER DROP CREATE CREATE statement is used to create various database objects for example DB2 table. View etc. and numeric . modify. you cannot compare columns containing incompatible data types. As shown in built-in data types have three general categories: datetime.

DB2 Guide Page 5 of 28 Signed Numeric INT Full word binary. 2 bytes DECIMAL (p. VARGRAPHIC(n) Variable Double byte character strings(DBCS)... GRAPHIC(n) Double byte character strings(DBCS). Maximum it uses 2n + 2 bytes depending upon n . n bytes. p/2 bytes String CHAR(n) 1 char is stored in 1 byte. I char is stored in two bytes. 4 bytes SMALLINT Half word binary. so this data type will take 2n bytes. 2 bytes is used for length and n bytes to store the actual data. q) Packed decimal. p is total size and q is number of decimal points. n can be maximum of 255 VARCHAR(n) Variable character maximum takes n + 2 bytes.

• UNIQUE. a referential constraint or check constraint. o The data type and length attribute (for example. blank is the default value. o For fixed-length strings. and the column cannot contain null values. YYYYMMDDHHMMSSnnnnnn. • A list of the columns that make up the table. stored in packed decimal format and it will take 3 bytes. the current value of the associated special register is the default value. you can use the following values: • NOT NULL. stored in packed decimal format and it will take 4 bytes. when the column has one of the following DB2-assigned defaults: o For numeric columns. o For datetime columns. For each column. o For variable-length strings.g. which names the table PRODUCT. a default value o Optionally. CURDATE DATE NOT NULL WITH DEFAULT SET ‘2006-08-08’ If user does not insert any value Db2 will insert ‘2006-08-08’ into this column. the empty string (string of zero-length) is the default value. Identifying defaults If you want to constrain the input or identify the default of a column. o You must separate each column description from the next with a comma. when the column cannot contain null values. CHAR(8)). Timestamp will take 10 bytes. Use the CREATE TABLE statement to create a table. including LOB strings. DATETIME HHMMSS. and enclose the entire list of column descriptions in parentheses. CURDATE DATE NOT NULL WITH DEFAULT SET NULL If user does not insert any value Db2 will insert Null into this column. For more information about data types o Optionally. . zero is the default value. when the value for each row must be unique. The following SQL statement creates a table named PRODUCT: The preceding CREATE statement has the following elements: • CREATE TABLE. E.DB2 Guide Page 6 of 28 Datetime DATE YYYYMMDD. SERIAL). specify the following information: o The column's name (for example. DEFAULT. TIMESTAMP Timestamp is nothing but date and time accurate up to nearest micro second.

2) CHECK EMPSAL > 0 DEPTNO INT CHECK(DEPTNO BETWEEN 1 AND 100) PRIMARY KEY Primary key value uniquely identifies the row FOREIGN KEY Foreign Key value identifies a row of related data.‘F’)) EMPSAL DECIMAL(7. Delete Rules When a row with primary key is deleted what should be done about the rows with matching keys. This constraint will be useful when you know the exclusive list of values that can be contained in that column. FOREIGN KEY(DEPT) REFERENCES DEPT_TAB(DEPTNO). A table can be parent of many dependents and it can also be dependent of many parents.DB2 Guide Page 7 of 28 Check Constraint We can restrict user to certain set of inputs.g. e. EMPSEX CHAR(1) CHECK (EMPSEX IN (‘M’. Designer chooses one of . The DEPT_TAB and EMP_TAB tables are related. REFERENTIAL INTEGRITY Referential Integrity maintains data validity by enforcing rules during processing so that ƒ Every primary key value is unique and is not null ƒ Every foreign key value matches a primary key. DEPT_TAB is parent table and EMP_TAB is dependent table. A dependent of dependent is a descendent table. (Usually the row being related is in another table) The table containing primary key is called as parent table and the one containing the foreign key is called as dependent table.

CLUSTERING INDEX . CREATE UNIQUE INDEX DEPT_TABX ON DEPT_TAB ( DEPTNO). The main advantage of using Index is faster access to DB2 data. INDEX It is set of pointers to DB2 tables. ƒ Restrict – delete request will be cancelled if there is at least one row in dependent table. If an index is unique. CREATE INDEX EMP_TABX ON EMP_TAB (EMPNO). E. CREATE INDEX CLUST_DEPT ON EMP_TAB (DEPTNO) CLUSTER.DB2 Guide Page 8 of 28 ƒ Cascade – if parent table row is deleted then all the matching rows in dependent table will also be deleted ƒ Set Null – if parent table row is deleted then all the matching columns (foreign key column) in dependent table will be set to null. DB2 will ensure that uniqueness is maintained (it will not allow another row with the same key to be added to the table).g.

as the user does not need to supply any descriptive informatiob to DB2 about the object being dropped. (Two columns can be added by using two ALTER statements) ALTER table can be used to add check constraints. Only one column can be added through an ALTER TABLE statement. the utility will rearrange the data rows into the same sequence as the entries in clustering index.g. and are accessed by a single read. Performance will improved if all of the rows for a single DEPT value were physically grouped together. ALTER A previously defined table can later be altered at any time. which makes it very easy to clear out large amounts of data. . ALTER TABLE EMP_TAB ADD DOJ AS DATE. In this case we alter table EMP_TAB by adding new column DOJ. All the indexes and views defined on the table will be dropped with the table. DROP The drop statement is simple in format. ALTER TABLE EMP_TAB ADD CHECK EMPSAL > 0. DROP type-of-object-dropped <name-of-object-being-dropped> E. DROP INDEX EMP_TABX. The DROP process has a powerful cascade effect. The most common alteration on a table is to add another column to it. Then we ask for all of C01 employees since all three of C01 rows are in a single page.DB2 Guide Page 9 of 28 Many users will want to see the group of rows for a single dept value. When REORG utility is executed. When the index is defined (via CREATE INDEX statement) add the CLUSTER at the end of the statement. Because an index or view is meaningless without a table.

’SSE’) INSERT INTO EMP_TAB_NEW SELECT * FROM EMP_TAB. E.’NAVEEN’. from the database table called "Persons". INSERT INTO EMP_TAB (EMPID. UPDATE.g. Note: SQL statements are not case sensitive.FirstName FROM Persons . delete. The SELECT statement is used to select data from a table.g. or select data from the database objects Using DML we can add or modify data in an existing table using the statements INSERT. SELECT is the same as select. The tabular result is stored in a result table (called the result-set). DESIG) VALUES (030. update. For e. E. UPDATE TABLE SET EMPSAL = EMPSAL + 1000. and DELETE: Inserting rows: INSERT Selecting values as you insert: SELECT from INSERT Updating current values: UPDATE Deleting rows: DELETE INSERT Insert statement is used to insert rows into db2 table. DEPT. To select the content of columns named "LastName" and "FirstName". SELECT [ALL/DISTINCT] scalar-expression (s) FROM table (s) [WHERE conditional-expression] [GROUP BY columns] [HAVING conditional expression] [ORDER BY columns] DISTINCT -> to eliminate duplicate rows The SQL SELECT Statement The SELECT statement is used to select data from a table. SELECT clause The select clause specifies the columns of the final result. use a SELECT statement like this: SELECT LastName. UPDATE Update statement is used to update existing row in a DB2 table. The tabular result is stored in a result table (called the result-set).DB2 Guide Page 10 of 28 DATA MANIPULATION LANGUAGE Statements insert.g.’C01’. NAME.

like this: SELECT * FROM Persons THE RESULT SET: The result from a SQL query is stored in a result-set. use a * symbol instead of column names. With SQL. The DISTINCT keyword is used to return only distinct (different) values. all we need to do is to add a DISTINCT keyword to the SELECT statement: Syntax SELECT DISTINCT column_name(s) FROM table_name To select ALL values from the column named "Company" we use a SELECT statement like this: SELECT Company FROM Orders "Orders" table Company OrderNumber Sega 3412 Lemuria 2312 Pepsi 4678 Lemuria 6798 Result Company Sega Lemuria Pepsi Lemuria .DB2 Guide Page 11 of 28 The database table "Persons": LastName FirstName Address City Rao Vivek Timoteivn 10 New York Pathi Narender Borgvn 23 New York Satya Kalyan Storgt 20 Washington The result LastName FirstName Rao Vivek Pathi Narender Satya Kalyan Select All Columns To select all columns from the "Persons" table.

and without the GROUP BY function it was impossible to find the sum for each individual group of column values. The OR operator displays a row if ANY of the conditions listed are true. LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Svendson Stephen Kaivn 18 Sandnes SELECT * FROM Persons WHERE (FirstName='Tove' OR FirstName='Stephen') AND LastName='Svendson' LastName FirstName Address City Svendson Tove Borgvn 23 Sandnes Svendson Stephen Kaivn 18 Sandnes To display the persons with LastName equal to "Hansen" or "Pettersen".. To select only DIFFERENT values from the column named "Company" we use a SELECT DISTINCT statement like this: SELECT DISTINCT Company FROM Orders Result: Company Sega Lemuria Pepsi AND & OR AND and OR join two or more conditions in a WHERE clause.. Syntax .'Pettersen') Result: LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Pettersen Kari Storgt 20 Stavanger GROUP BY GROUP BY. use the following SQL: SELECT * FROM Persons WHERE LastName IN ('Hansen'. The AND operator displays a row if ALL conditions listed are true. was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called.DB2 Guide Page 12 of 28 Note that "Lemuria" is listed twice in the result-set.

SUM(Amount) FROM Sales Returns this result: Company SUM(Amount) W3Schools 17100 IBM 17100 W3Schools 17100 The above code is invalid because the column returned is not part of an aggregate..SUM(column) FROM table GROUP BY column E. it would be impossible to test for result conditions.SUM(Amount) FROM Sales GROUP BY Company Returns this result: Company SUM(Amount) W3Schools 12600 IBM 4500 HAVING HAVING..SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value This "Sales" Table: Company Amount W3Schools 5500 IBM 4500 W3Schools 7100 . was added to SQL because the WHERE keyword could not be used against aggregate functions (like SUM). This "Sales" Table: Company Amount W3Schools 5500 IBM 4500 W3Schools 7100 SELECT Company.. A GROUP BY clause will solve this problem: SELECT Company. Syntax SELECT column..g.DB2 Guide Page 13 of 28 SELECT column. and without HAVING.

You can use a SELECT statement to retrieve and join column values from two or more tables into a single row. NORMALIZATION Is a process of decomposing a relation into smaller structured relations. But dropping a table or view does drop its synonyms. It is a process which promotes Data integrity and reduces data redundancy. Two relations T1 and T2 are said to be union compatible if I). you might want to retrieve some column values from one table and some column values from another table. both T1 and T2 contain same number of columns II). SELECT ENO FROM EMPMASTER WHERE ESAL > 5000 UNION SELECT ENO FROM ETAB WHERE DEPT=’CSE’ -> Duplicates are always removed from the result table unless the union operator explicitly includes the ALL qualifier. Dropping a table or view has no effect on its aliases. A synonym is an unqualified name that can only be used by the authorization ID that created it. If Ith column of T1 is compatible with Ith column of T2. To form a row of the result table.g. but the two relations (tables) must be union compatible. An alias is a qualified name that can be used by any authorization ID. . SUM(Amount) FROM Sales GROUP BY Company HAVING SUM(Amount)>10000 Returns this result Company SUM(Amount) W3Schools UNION UNION combine two sets of rows into single set. e.DB2 Guide Page 14 of 28 This SQL: SELECT Company. JOIN Sometimes the information that you want to see is not in a single table. Following are the differences between them. DB2 supports the following types of joins: Inner join Left outer join Right outer join Full outer join. ALIAS AND SYNONYM Both are alternate names for a table.

g.PROD# = PRODUCT. Inner Join: Extracts only matching rows from Left and Right table Full Outer Join: Extracts matching as well as unmatching rows from left and right table Left Outer Join: Extracts matching rows and unmatching rows from left table Right Outer Join: Extracts matching rows and unmatching rows from right table e.PROD# VIEW View is a virtual table (i.] AS subquery .PROD#.column2….. COALESE( PARTS.PRODUCT.DB2 Guide Page 15 of 28 You can specify joins in the FROM clause of a query.e. it is not present physically) which is defined from other tables.PROD#). SELECT PART. General syntax of CREATE VIEW CREATE VIEW view-name [(column2[.PRICE FROM PARTS OUTER JOIN PRODUCTS ON PARTS.

DB2 Guide Page 16 of 28 [WITH CHECK OPTION]. Group by or Having at outermost level Distinct View involving subquery on same table . Column of the view is derived from aggregate function. subquery cannot contain UNION or ORDER BY All views are non updatable VIEW becomes non-updatable if If a column of the view is derived from an expression involing a scalar operator or a scalar function.

prepared and executed at runtime DB2 PROGRAM PREPARATION Static SQL statements are generally preferable to dynamic SQL statements (prepared by DB2 at execution time) because they typically are more efficient (since in dynamic sql binding is done at execution time). . The first step in DB2 program preparation is writing a program that contains embedded SQL statements. These programs are called as embedded SQL programs. Dynamic SQL In dynamic SQL the statements are constructed. this is done by DB2 precompiler. Before passing this program to COBOL compiler we need to take out SQL statements because COBOL compilers cannot recognize SQL.DB2 Guide Page 17 of 28 EMBEDDED SQL Static SQL In static SQL the statement is prepared before execution.

Access authorization Database object validation The output of the bind process is a control structure that DB2 will use to execute the SQL statements when the application program is run. 2. Functions of Bind Syntax Checking Qualifying object names Access path selection (optimization). called a consistency token(timestamp). and inserts a call to DB2 for each statement. A database request module (DBRM). A modified program source module.DB2 Guide Page 18 of 28 The DB2 precompiler processes it and generates two outputs: 1. The precompiler places a unique identifier. A DBRM contains the SQL statements found in the program source. Following the precompile process. The precompiler comments out each of the program's embedded SQL statements. you compile and link-edit the modified source program into an executable load module and bind the associated DBRM. In the DB2 for OS/390 bind process. into each of these outputs. These consistency tokens are better understood when we get to program execution. . The control structure will either be part of a plan (if the DBRM is bound directly into a plan) or contained within a package that will be executed via a plan.

You can rebind one package quickly. Package contains machine code of best access path. you only have to rebind one package. during which the plan cannot be executed. on the other hand. programs are bound directly into plans. If. BIND PACKAGE(COL1) – MEMBER(PGM1) Package of PGM1 will be created in collection COL1. • Improved availability.g. package can be executed via plan. BIND PACKAGE(collection name) - MEMBER(dbrm name) e. and it's important to do so: A package cannot be executed while it's being rebound. a change of one SQL statement requires that the plan be rebound. Package is not executable independently.. Collection is physical collection of packages. both packages and collections are stored in DB2 directory. If you use the package bind process. you have to bind the package into what is called a collection. the rebind could take a fair amount of time. . If you change a SQL statement in a program. How do you create a collection? Pretty simple: You bind a package into it. and it offers some important advantages over plan-direct binds.DB2 Guide Page 19 of 28 The DB2 package bind process has been around for quite some time (since DB2 version 2 release 3). If you've bound a large number of DBRMs into the plan.

DB2 throws Sqlcode -805. When such a program requests some database operation. Plan is executable..DB2 Guide Page 20 of 28 List of packages will be input to BIND PLAN process the main function of BIND PLAN process is to create application plan from packages. Say that if the corresponding package is not found in the plan. BIND PLAN(Plan name) - PKLIST(collection_name.) e. storing and retrieving records as requested by application plans When controls go to Application plan first it will search for corresponding program name when it finds that (package) it will search for corresponding access path using consistency token (nothing but timestamp inserted by Pre-compiler. control goes first to the Runtime Supervisor according to the CALLs inserted by the pre-compiler. A Data Manager manages the actual database. BIND PLAN(PLAN1) - PKLIST(COL1.g.*) Now we have two executable components LOAD MODULE from modified source and APPLICATION PLAN from DBRM.COL2. The Runtime Supervisor then routes control to the application plan and the application plan in turn.PGM1. A Runtime Supervisor oversees SQL application programs during execution. invokes a Data Manager to perform the required function.…. When it finds that it performs the required action using Data manager and buffer manager.package_name. APPLICATION PLAN or PLAN: it is set of pointers to packages (like index pointing to data) or we can say plan is logical collection of packages. -805 -> Program name not found in plan. .

and the data type of each column. DECLARING TABLE AND VIEW DEFINITIONS Before your program issues SQL statements that select. Use EXEC SQL and END-EXEC. How to resolve -818? Bind the DBRMs again. you should declare the tables and views that your program accesses. update. the DECLARE statement specifies the structure of the table or view you are working with. to delimit an SQL statement in a COBOL program: EXEC SQL an SQL statement END-EXEC. insert. One way to declare a table or view is to code a DECLARE statement in the WORKING-STORAGE SECTION or LINKAGE SECTION within the DATA DIVISION of your COBOL program. Another advantage is that the DB2 precompiler uses your declarations to make sure that you have used correct column names and data types in your SQL statements. it may not be pointing to required package. You can use one of the following methods: o Static SQL o Embedded dynamic SQL • Declare the tables that you use • Declare the data items for passing data between DB2 and a host language. Specify the name of the table . You can refer to the DECLARE statement for the column names and data types in the table or view. You do not need to declare tables or views. • Choose a method for communicating with DB2. The DB2 precompiler issues a warning message when the column names and data types do not correspond to the SQL DECLARE statements in your program. according to the host language rules. How to code an embedded SQL program ‘or’ Basics of coding SQL in an application program Following are the steps which should be followed while coding an embedded SQL program.DB2 Guide Page 21 of 28 -818 -> Timestamp mismatch in load module and application plan. For example. To do this. but doing so offers advantages. One advantage is documentation. or delete data. How to resolve -805? Check the PKLIST in BIND PLAN. • Declare an SQL communications area (SQLCA) • Code SQL statements to access DB2 data. Means corresponding program is found in plan but in that package there is no access path matching with the timestamp of load module. include an SQL DECLARE statement in your program.

DEPT table looks like the following DECLARE statement in COBOL: As an alternative to coding the DECLARE statement yourself.s) S9(p)V or S9(p). use S9(p-s)V9(s) COMP-3 NUMERIC(p. the input can be given as text. The inner variables must VARCHAR(n) 49 VAR-LEN PIC S9(4) USAGE COMP-3. For TIMESTAMP are stored in DATE example. For example. Fixed-length character string of length of length n. INTEGER S9(9) COMP p is precision. Internally DATE. If s=0.DB2 Guide Page 22 of 28 and list each column and its data type. use SV9(s). DECIMAL(p. For TIME example. In addition to these basic requirements. But 01 VAR-NAME PIC X(n). you specify DECLARE table-name TABLE regardless of whether the table-name refers to a table or a view. s is scale. If s=p. you can use DCLGEN. CHAR(n) 1<=n<=255 01 VAR-NAME PIC X(n). TIMESTAMP For example. have a level of 49. (DCLGEN can be created by option 2 in DB2 Interactive menu). When you declare a table or view. packed decimal format. the DECLARE TABLE statement for the SSS033. For example. 01 VAR-NAME PIC X(n). Fixed-length character string of length n. REAL or FLOAT (n) COMP-1 1<=n<=21 DOUBLE PRECISION. For example. 01 VAR-NAME PIC X(n). DETERMINING EQUIVALENT SQL AND COBOL DATA TYPES SQL data type COBOL data type Notes SMALLINT S9(4) COMP. you should also consider the following special topics: . 49 VAR-TEXT PIC X(n). Varying-length character string. 01 VAR-NAME. COMP-2 22<=n<=53 DOUBLE or FLOAT (n) Fixed-length character string. TIME and Fixed-length character string of length n. the declarations generator that is supplied with DB2.s) or 0<=s<=p<=31.

• DCLGEN —how to use DB2's declarations generator.EDCL – GENERAL EMPLOYEE INFO * * SSS035. INPUT-OUTPUT SECTION. 05 EMP-SSN PIC 9(10). . 05 EMP-BASIC PIC 9(8)V9(2). A program that contains executable SQL statements (except for DECLARE.PDCL – PAY INFORMATION OF AN EMPLOYEE * * * * CREATED NARENDER KUMAR PATHI AUG 2006 * * * ****************************************************************** ENVIRONMENT DIVISION. FILE SECTION. ****************************************************************** * * * TITLE INVALID GROUP ACCOUNT REPORT * * * * DESCRIPTION THIS PROGRAM WILL READ INFORMATION FROM EMPLOYEE * * FILE AND INSERTS THE SAME DATA IN EDCL AND PDCL * * TABLES * * * INPUT EMP – EMPLOYEE FILE THAT HAVE EMPLOYEE INFORMATION* * * * OUTPUT N/A * * * * DB2 OBJECTS SSS035. DCLGEN. to obtain accurate SQL DECLARE statements for tables and views. 05 EMP-DOB PIC X(10). DATA DIVISION. SELECT EMP-FILE ASSIGN TO EMP. PROGRAM-ID. and WHENEVER) The SQL INCLUDE statement can be used to provide the declaration of the SQLCA EXEC SQL INCLUDE SQLCA END-EXEC Simple COBOL DB2 program which reads from a file and inserts into a table IDENTIFICATION DIVISION. INSPGM. INCLUDE. FD EMP-FILE.DB2 Guide Page 23 of 28 • Cursors — to use a cursor in your application program to select a set of rows and then process the set either one row at a time or one row set at a time. 05 EMP-NAME PIC X(20). 05 EMP-DOJ PIC X(10). 05 EMP-ADDRESS PIC X(100). 05 EMP-ID PIC 9(10). INCLUDE SQL COMMUNICATIONS AREA (SQLCA) An SQLCA is a collection of variables that is updated at the end of the execution of every SQL statement. FILE-CONTROL. 01 EMP-REC.

10 EV-EMPNAME PIC X(20). GROSS DECIMAL(10. ****************************************************************** * DECLARATION OF TABLE SSS035.EDCL * ****************************************************************** 01 DCLEDCL. 01 WORK-AREAS. OPEN INPUT EMP-FILE. HRA DECIMAL(10. BASIC DECIMAL(10. 10 EV-DOB PIC X(10). ****************************************************************** * HOST VARIABLE DECLARATION OF TABLE SSS035. ITAX DECIMAL(10. 10 HV-EMPID PIC S9(9) USAGE COMP. 2). 2). 2). ****************************************************************** * DECLARATION OF TABLE SSS035. 10 HV-ITAX PIC S9(8)V9(2) USAGE COMP-3. EMPNAME CHAR(20). 10 EV-SSN PIC S9(10)V USAGE COMP-3. SSN DECIMAL(10. 05 WS-SQLCODE PIC -9(4). DOB DATE. 0). READ EMP-FILE AT END SET EMP-EOF TO TRUE END-READ IF EMP-EOF . 10 HV-HRA PIC S9(8)V9(2) USAGE COMP-3. 10 EV-DOJ PIC X(10). ADDRESS CHAR(100)) END-EXEC. 10 EV-ADDRESS PIC X(100). 2)) END-EXEC. NETSAL DECIMAL(10.PDCL * ****************************************************************** 01 DCLPDCL.EDCL TABLE ( EMPID INTEGER NOT NULL. 05 WS-EMP-EOF PIC X VALUE 'N'. 10 HV-GROSS PIC S9(8)V9(2) USAGE COMP-3.PDCL * ****************************************************************** EXEC SQL DECLARE SSS035.PDCL TABLE ( EMPID INTEGER NOT NULL. WORKING-STORAGE SECTION.EDCL * ****************************************************************** EXEC SQL DECLARE SSS035. DOJ DATE.DB2 Guide Page 24 of 28 05 FILLER PIC X(130). 10 HV-BASIC PIC S9(8)V9(2) USAGE COMP-3. PROCEDURE DIVISION. 0000-MAIN-PARA. 10 HV-NETSAL PIC S9(8)V9(2) USAGE COMP-3. ****************************************************************** * HOST VARIABLE DECLARATION OF TABLE SSS035. 88 EMP-EOF VALUE 'Y'. 10 EV-EMPID PIC S9(9) USAGE COMP. EXEC SQL INCLUDE SQLCA END-EXEC. 2).

.EDCL(EMPID.20 COMPUTE HV-GROSS = HV-BASIC + HV-HRA COMPUTE HV-NETSAL = HV-GROSS . 1000-PROCESS-PARA. :EV-DOB. DOJ. NETSAL) VALUES(:HV-EMPID. HRA. :HV-BASIC.. . :EV-ADDRESS) END-EXEC IF SQLCODE = 0 ************************************************ * INSERT INTO PAY TABLE * ************************************************ EXEC SQL INSERT INTO SSS035. DOB. :HV-HRA.. ADDRESS) VALUES(:EV-EMPID. :EV-EMPNAME.DB2 Guide Page 25 of 28 DISPLAY " EMPTY INPUT FILE... ITAX. SSN. :HV-ITAX. GROSS." END-IF PERFORM 1000-PROCESS-PARA UNTIL EMP-EOF CLOSE EMP-FILE GOBACK .60 COMPUTE HV-ITAX = HV-BASIC * 0.. READ EMP-FILE AT END MOVE 'Y' TO WS-EMP-EOF END-READ ************************************************ * POPULATE EMP TABLE HOST VARIABLES * ************************************************ MOVE EMP-ID TO EV-EMPID MOVE EMP-NAME TO EV-EMPNAME MOVE EMP-SSN TO EV-SSN MOVE EMP-DOJ TO EV-DOJ MOVE EMP-DOB TO EV-DOB MOVE EMP-ADDRESS TO EV-ADDRESS ************************************************ * POPULATE PAY TABLE HOST VARIABLES * ************************************************ MOVE EMP-ID TO HV-EMPID MOVE EMP-BASIC TO HV-BASIC COMPUTE HV-HRA = HV-BASIC * 0. :EV-DOJ. BASIC. EMPNAME. :EV-SSN.HV-ITAX ************************************************ * INSERT INTO EMP TABLE * ************************************************ EXEC SQL INSERT INTO SSS035.PDCL(EMPID.

. :HV-NETSAL) END-EXEC IF SQLCODE = 0 DISPLAY " RECORDS INSERTED. move 0 to the null indicator CURSOR COBOL program cannot handle more than one row at a time. 0. -2? -1 : the field is null 0 : the field is not null -2 : the field value is truncated How to Insert a record with a nullable column? To insert a NULL... What does it mean if the null indicator has -1....DB2 Guide Page 26 of 28 :HV-GROSS.. INTO: HOSTVAR [INDICATOR] : NULLIND otherwise DB2 throws error. Cursor is used to extract more than one row from DB2 table or View..." ELSE MOVE SQLCODE TO WS-SQLCODE DISPLAY "ERROR OCCURRED IN PAY TABLE " WS-SQLCODE END-IF ELSE MOVE SQLCODE TO WS-SQLCODE DISPLAY "ERROR OCCURRED IN EMP TABLE " WS-SQLCODE END-IF.. Syntax .. Steps involved in a program using Cursor DECLARE OPEN FETCH CLOSE DECLARE DECLARE cursor-name CURSOR [WITH HOLD] FOR Select expression [FOR FETCH ONLY/ FOR UPDATE OF column_name] [OPTIMIZE FOR n ROWS] . HOW TO HANDLE NULL VALUES Use null indicators.... SQLCODE = -305. move -1 to the null indicator To insert a valid value.. The picture clause of the null indicator variable S9(4) COMP.

DB2 Guide Page 27 of 28 Options WITH HOLD – if you don’t specify WITH HOLD cursor will be closed when you issue COMMIT DB2 closes the cursor and you will lose the current position of the cursor. If the package already exists. If you want to retain the position of the CURSOR we need to specify this option. Fetch is like a sequential read from a file. and that a new package is to be created. OPTIMIZE FOR n ROWS – If you inform BIND about approximate number of rows that may be retrieved for your select expression then BIND OPTIMIZER can choose more appropriate access method which will improve performance of the SQL statement however if you give wrong estimate it can degrade the performance as well so you should be careful while using this option OPEN Before fetching from Cursor first we should open it. FOR UPDATE OF is used when you want to update any column so that DB2 can apply appropriate lock. ADD Indicates that the named package does not exist. and a diagnostic error message is returned. FOR FETCH ONLY/ FOR UPDATE OF – FOR FETCH ONLY is used when you want to just read so that DB2 will apply locks accordingly. REPLACE . EXEC SQL FETCH cursor_name INTO host variables END-EXEC CLOSE After all the operations the cursor should be closed. This option is just for better locking its nothing to do with the result produced by the cursor. Query in cursor will be executed when we open it (not at the time of declare) EXEC SQL OPEN cursor_name END-EXEC FETCH Fetch reads a row sequentially from result set. execution stops. EXEC SQL CLOSE cursor_name END-EXEC Simple COBOL DB2 program which reads from a table based on department and stores in corresponding file BIND OPTIONS ACTION Indicates whether the package can be added or replaced.

ISOLATION Determines how far a program bound to this package can be isolated from the effect of other executing programs. This DRDA precompile/bind option is not supported by DB2 for Windows and UNIX. This is the default value for the ACTION option. EXPLAIN Stores information in the Explain tables about the access plans chosen for each SQL statement in the package NO Explain information will not be captured. or when the application terminates. CS Specifies Cursor Stability as the isolation level When controls mo RR Specifies Repeatable Read as the isolation level UR Specifies Uncommitted Read as the isolation level RELEASE Indicates whether resources are released at each COMMIT point. COMMIT Release resources at each COMMIT point. YES Explain tables will be populated with information about the chosen access plan at prep/bind time for static statements and at run time for incremental bind statements. DEALLOCATE Release resources only when the application terminates .DB2 Guide Page 28 of 28 Indicates that the existing package is to be replaced by a new one with the same package name and creator. Used for dynamic SQL statements.