DB2 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 (reco rds) and columns (fields). All access to and manipulation of data in DB2 is acco mplished 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 m ore 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 directory. 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 dat abase DB2 Tablespace DB2 Guide Page 3 of 28 Tablespace is physical collection of tables and their associated indexes. Tables paces uses one or more VSAM linear datasets (LDS) and the maximum size of Tables pace is 64GB. A Tablespace is divided into equal sized units (of 4k bytes), call ed pages which are written to or read from DASD in one operation. In order to service a request to see one byte of data, DB2 brings in the 4K page containing that byte. DB2 Storage Groups A DB2 storage group is a set of volumes on direct access storage devices (DASD). Volume holds the datasets in which tablespaces and indexes are actually stored. A database can be stored in one or more storage groups. DB2 tables DB2 tables holds data in the form of rows and columns. DB2 Index An Index is an ordered set of pointers to data in a DB2 table. An index space is automatically defined in the same database as the table. DB2 Views View is a virtual table defined on another table or view. The data only exist in the base table only the definition of view is stored. DB2 Catalog The DB2 catalog consists of a group of tables containing information about other objects with in the DB2 subsystem. When you create, alter, or drop any object, DB2 inserts, updates, or deletes rows of the catalog tables that describe the ob ject and also have the information how this object relates to other objects. Users have read access to these tables. Some of the tables in DB2 catalog are SYSTABLES Contains one row for each table, 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 manipulati ng data. All SQL statements should be prepared (Bind) before they can be execute d. The result of preparation is executable form of statement (plan). Static SQL In static SQL the statement is prepared before execution. Dynamic SQL In dynamic SQL the statements are constructed, prepared and executed at runtime. We can divide sql into three different categories. Data Definition Language Statements create, modify, or drop database objects Data Manipulation Language statements insert, update, delete, or select data from the database objects Transaction Control Language statements grant or revoke privileges or authorities to perform database operati ons on the objects in your database DB2 Guide Page 4 of 28 DATA DEFINITION LANGUAGE Statements create, modify, or drop database objects. Statements Available CREATE ALTER DROP CREATE CREATE statement is used to create various database objects for example DB2 tabl e, Index, Tablespace, View etc. e.g. 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. When you perform operations on columns, the data must be compatible with the da ta type of the referenced column. For example, you cannot insert character data, like a last name, into a column whose data type is numeric. Similarly, you cann ot compare columns containing incompatible data types. To better understand the concepts that are presented in this section, you must u nderstand the data types of the columns to which an example refers. As shown in built-in data types have three general categories: datetime, string, and numeric DB2 Guide Page 5 of 28 Signed Numeric INT Full word binary, 4 bytes SMALLINT Half word binary, 2 bytes DECIMAL (p, q) Packed decimal, p is total size and q is number of decimal points. p/2 bytes String CHAR(n) 1 char is stored in 1 byte, n bytes., n can be maximum of 255 VARCHAR(n) Variable character maximum takes n + 2 bytes. 2 bytes is used for length and n bytes to store the actual data. GRAPHIC(n) Double byte character strings(DBCS), I char is stored in two bytes., so this dat a type will take 2n bytes. VARGRAPHIC(n) Variable Double byte character strings(DBCS), Maximum it uses 2n + 2 bytes depen ding upon n DB2 Guide Page 6 of 28 Datetime DATE YYYYMMDD, stored in packed decimal format and it will take 4 bytes. DATETIME HHMMSS, stored in packed decimal format and it will take 3 bytes. TIMESTAMP Timestamp is nothing but date and time accurate up to nearest micro second. YYYYMMDDHHMMSSnnnnnn. Timestamp will take 10 bytes. Use the CREATE TABLE statement to create a table. The following SQL statement cr eates a table named PRODUCT: The preceding CREATE statement has the following elements: CREATE TABLE, which names the table PRODUCT. A list of the columns that make up the table. For each column, specify the follo wing information: o The column's name (for example, SERIAL). o The data type and length attribute (for example, CHAR(8)). For more informatio n about data types o Optionally, a default value o Optionally, a referential constraint or check constraint. o You must separate each column description from the next with a comma, and encl ose the entire list of column descriptions in parentheses. Identifying defaults If you want to constrain the input or identify the default of a column, you can use the following values: NOT NULL, when the column cannot contain null values. UNIQUE, when the value for each row must be unique, and the column cannot contai n null values. DEFAULT, when the column has one of the following DB2-assigned defaults: o For numeric columns, zero is the default value. o For fixed-length strings, blank is the default value. o For variable-length strings, including LOB strings, the empty string (string o f zero-length) is the default value. o For datetime columns, the current value of the associated special register is the default value. E.g. CURDATE DATE NOT NULL WITH DEFAULT SET NULL If user does not insert any value Db2 will insert Null into this column. 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. DB2 Guide Page 7 of 28 Check Constraint We can restrict user to certain set of inputs, This constraint will be useful wh en you know the exclusive list of values that can be contained in that column. e.g. EMPSEX CHAR(1) CHECK (EMPSEX IN ( M , F )) EMPSAL DECIMAL(7,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. (Usually the row being relat ed is in another table) The table containing primary key is called as parent table and the one containin g the foreign key is called as dependent table. A dependent of dependent is a de scendent table. A table can be parent of many dependents and it can also be dependent of many pa rents. The DEPT_TAB and EMP_TAB tables are related. DEPT_TAB is parent table and EMP_TAB is dependent table. FOREIGN KEY(DEPT) REFERENCES DEPT_TAB(DEPTNO). REFERENTIAL INTEGRITY Referential Integrity maintains data validity by enforcing rules during processi ng so that ?? Every primary key value is unique and is not null ?? Every foreign key value matches a primary key. Delete Rules When a row with primary key is deleted what should be done about the rows with m atching keys. Designer chooses one of DB2 Guide Page 8 of 28 ?? Cascade if parent table row is deleted then all the matching rows in dependen t table will also be deleted ?? Set Null if parent table row is deleted then all the matching columns (foreig n key column) in dependent table will be set to null. ?? Restrict delete request will be cancelled if there is at least one row in dep endent table. INDEX It is set of pointers to DB2 tables. If an index is unique, DB2 will ensure that uniqueness is maintained (it will not allow another row with the same key to be added to the table). The main advantage of using Index is faster access to DB2 data. E.g. CREATE INDEX EMP_TABX ON EMP_TAB (EMPNO); CREATE UNIQUE INDEX DEPT_TABX ON DEPT_TAB ( DEPTNO); CREATE INDEX CLUST_DEPT ON EMP_TAB (DEPTNO) CLUSTER; CLUSTERING INDEX DB2 Guide Page 9 of 28 Many users will want to see the group of rows for a single dept value. Performan ce will improved if all of the rows for a single DEPT value were physically grou ped together. Then we ask for all of C01 employees since all three of C01 rows a re in a single page, and are accessed by a single read. When the index is defined (via CREATE INDEX statement) add the CLUSTER at the en d of the statement. When REORG utility is executed, the utility will rearrange t he data rows into the same sequence as the entries in clustering index. ALTER A previously defined table can later be altered at any time. The most common alteration on a table is to add another column to it. In this ca se we alter table EMP_TAB by adding new column DOJ. ALTER TABLE EMP_TAB ADD DOJ AS DATE; Only one column can be added through an ALTER TABLE statement. (Two columns can be added by using two ALTER statements) ALTER table can be used to add check constraints. ALTER TABLE EMP_TAB ADD CHECK EMPSAL > 0; DROP The drop statement is simple in format, as the user does not need to supply any descriptive informatiob to DB2 about the object being dropped. DROP type-of-object-dropped <name-of-object-being-dropped> E.g. DROP INDEX EMP_TABX; The DROP process has a powerful cascade effect, which makes it very easy to clea r out large amounts of data. All the indexes and views defined on the table will be dropped with the table. Because an index or view is meaningless without a ta ble. DB2 Guide Page 10 of 28 DATA MANIPULATION LANGUAGE Statements insert, update, delete, or select data from the database objects Using DML we can add or modify data in an existing table using the statements IN SERT, UPDATE, 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. E.g. INSERT INTO EMP_TAB (EMPID, DEPT, NAME, DESIG) VALUES (030, C01 , NAVEEN , SSE ) INSERT INTO EMP_TAB_NEW SELECT * FROM EMP_TAB; UPDATE Update statement is used to update existing row in a DB2 table. For e.g. UPDATE TABLE SET EMPSAL = EMPSAL + 1000; SELECT clause The select clause specifies the columns of the final result. The SELECT statemen t is used to select data from a table. The tabular result is stored in a result table (called the result-set). 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. The tabular result is stored in a result table (called the result-set). Note: SQL statements are not case sensitive. SELECT is the same as select. E.g. To select the content of columns named "LastName" and "FirstName", from the data base table called "Persons", use a SELECT statement like this: SELECT LastName,FirstName FROM Persons 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, use a * symbol instead of column names, like this: SELECT * FROM Persons THE RESULT SET: The result from a SQL query is stored in a result-set. The DISTINCT keyword is used to return only distinct (different) values. With SQL, 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 l ike 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 12 of 28 Note that "Lemuria" is listed twice in the result-set. 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. The AND operator displays a row if ALL conditions listed are true. The OR operat or 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", use the f ollowing SQL: SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') Result: LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Pettersen Kari Storgt 20 Stavanger GROUP BY GROUP BY... was added to SQL because aggregate functions (like SUM) return the a ggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of colum n values. Syntax DB2 Guide Page 13 of 28 SELECT column,SUM(column) FROM table GROUP BY column E.g. This "Sales" Table: Company Amount W3Schools 5500 IBM 4500 W3Schools 7100 SELECT Company, 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 aggregat e. A GROUP BY clause will solve this problem: SELECT Company,SUM(Amount) FROM Sales GROUP BY Company Returns this result: Company SUM(Amount) W3Schools 12600 IBM 4500 HAVING HAVING... was added to SQL because the WHERE keyword could not be used against a ggregate functions (like SUM), and without HAVING... it would be impossible to t est for result conditions. Syntax SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value This "Sales" Table: Company Amount W3Schools 5500 IBM 4500 W3Schools 7100 DB2 Guide Page 14 of 28 This SQL: SELECT Company, 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, but the two relations (tables) m ust be union compatible. Two relations T1 and T2 are said to be union compatible if I). both T1 and T2 contain same number of columns II). If Ith column of T1 is compatible with Ith column of T2. e.g. 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. NORMALIZATION Is a process of decomposing a relation into smaller structured relations. It is a process which promotes Data integrity and reduces data redundancy. ALIAS AND SYNONYM Both are alternate names for a table. Following are the differences between them . Dropping a table or view has no effect on its aliases. But dropping a table or v iew does drop its synonyms. An alias is a qualified name that can be used by any authorization ID. A synonym is an unqualified name that can only be used by the authorization ID that creat ed it. JOIN Sometimes the information that you want to see is not in a single table. To form a row of the result table, you might want to retrieve some column values from o ne table and some column values from another table. You can use a SELECT stateme nt to retrieve and join column values from two or more tables into a single row. DB2 supports the following types of joins: Inner join Left outer join Right outer join Full outer join. DB2 Guide Page 15 of 28 You can specify joins in the FROM clause of a query. 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.g. SELECT PART, COALESE( PARTS.PROD#,PRODUCT.PROD#),PRICE FROM PARTS OUTER JOIN PRODUCTS ON PARTS.PROD# = PRODUCT.PROD# VIEW View is a virtual table (i.e., it is not present physically) which is defined fr om other tables. General syntax of CREATE VIEW CREATE VIEW view-name [(column2[,column2 .] AS subquery DB2 Guide Page 16 of 28 [WITH CHECK OPTION]; 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. Column of the view is derived from aggregate function. Group by or Having at outermost level Distinct View involving subquery on same table DB2 Guide Page 17 of 28 EMBEDDED SQL Static SQL In static SQL the statement is prepared before execution. Dynamic SQL In dynamic SQL the statements are constructed, prepared and executed at runtime DB2 PROGRAM PREPARATION Static SQL statements are generally preferable to dynamic SQL statements (prepar ed 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 emb edded SQL statements. These programs are called as embedded SQL programs. Before passing this program to COBOL compiler we need to take out SQL statements becau se COBOL compilers cannot recognize SQL, this is done by DB2 precompiler. DB2 Guide Page 18 of 28 The DB2 precompiler processes it and generates two outputs: 1. A modified program source module. The precompiler comments out each of the pr ogram's embedded SQL statements, and inserts a call to DB2 for each statement. 2. A database request module (DBRM). A DBRM contains the SQL statements found in the program source. The precompiler places a unique identifier, called a consistency token(timestamp ), into each of these outputs. These consistency tokens are better understood wh en we get to program execution. Following the precompile process, 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, Functions of Bind Syntax Checking Qualifying object names Access path selection (optimization), Access authorization Database object validation The output of the bind process is a control structure that DB2 will use to execu te the SQL statements when the application program is run. The control structure will either be part of a plan (if the DBRM is bound directly into a plan) or co ntained within a package that will be executed via a plan. DB2 Guide Page 19 of 28 The DB2 p lease 3), and it offers one be mber nnot w do you crea BIND PACKA MEMBER( e.g., BIND PACKA MEMBER(P Package of P Package ge can be ackage bind process has been around for quite some time (since DB2 version 2 res ome important advantages over plan-direct binds. Improved availability. If you c hange a SQL statement in a program, you only have to rebind package. You can reb ind one package quickly, and it's important to do so: A package cannot executed while it's being rebound. If, on the other hand, programs are bound directly int o plans, a change of one SQL statement requires that the plan be rebound. If you 've bound a large nuof DBRMs into the plan, the rebind could take a fair amount of time, during which the plan cabe executed. If you use the package bind proces s, you have to bind the package into what is called a collection. Hote a collect ion? Pretty simple: You bind a package into it. GE(collection name) - dbrm name) GE(COL1) GM1) GM1 will be created in collection COL1. contains machine code of best access path. Package is not executable independently; packa executed via pl an. Collection is physical collection of packages, both packages and collections are stored in DB2 directory. DB2 Guide Page 20 of 28 List of packages will be input to BIND PLAN process th APPLICATION PLAN or PL BIND PLAN(Plan name) - DB2 Guide Page 21 of 28 -818 -> Timestamp mismatch in load module and application plan. Means correspond ing program is foundplan but in that package there is n How to resolve -805? Followi Choose a method for communicating with DB2. You can use one of the following met hods: o Static SQL Declare the tables that you use Declare the data items for passing data between DB2 and a host language, according to the host language rules. Declare an SQL co mmunications area (SQLCA) Code SQL statements to access DB2 data. Use EXEC SQL and END-EXEC. to delimit an SQL statement in a COBOL proEXEC SQL an SQL statementEND-EXEC. DECLARING TABLE AND VIEW DEFINITIONS Before your program issues SQL statements that select, insert, update, or delete the tables and vie ws that your program accesses. To do this, incluprogram. You do not need to decl are tables or views, but doing so offers advantages. Ondocumentation. For exampl e, the DECLARE statement specifies the struworking with, and the data type of ea ch column. You can refer to the DECLARE names and data types in the table or view. Another advantage is that the DB2 pre compiler uses your declarations to make sure that you have used correct column n ames and data types in your SQL statementThe DB2 precompiler issues a warning me ssage when the column names and data types do not corresponto the SQL DECLARE st atements in your program. One way to declare a table or view is to code a DECLARE statement in the WORKING -ST DB2 Guide Page 22 of 28 and list each column and its data type. When you declare a table or view, you sp ecify DECLARE table-name TABLE regardless of whether the table-name refers to a table or a view. For example, the DECL As an alternative to coding the DECLARE statement yourself, you can use DCLGEN, the dec r that is supplied with DB2. (DCLGEN can be created by option 2 in DB2 Interacti ve menu). G EQUIVALENT SQL AND CO data type COBOL d T GER S9(9) COMP D N REAL or FLOAT (n) COMP-1 DOUBLE or FLOAT CHAR(n) VARCHAR(n) 01 VAR-NAME. 49 VAR-TEXT PIC X(n). 01 VAR-NAME PIC X(n). Internally DATE, TIMthe inputext. TIME Fixed-length charac ter string of length n. For example, 01 VAR-NAME PIC X(n). Fixed-length characte 01 VAR-NAME PIC X(n). DB2 Guide Page 23 of 28 set either one row at a time or one row set at a time. statements for tables and views. INCLUDE SQL COMMUNICATIONS AREA (SQLCA) An SQLC A is a collection of variables that is updated program that contains executable SQL statements (excThe SQL INCLUDE statement can be used to provide EXEC SQL INCLUDE SQLCA END-EXEC S PR GM. ************** ** * * TVALID GROUP * * DESCRI IS PROGRAM WILL RLOYEE * * LE AND INSERTS THPDCL * * * * INPUT P EMPLRMATION* * * * OUTPUT A * * S035.EDCL GENERAL EMPLOYEE INFO * * CRE RENDER KUMAR * * * TION. ILE ASSI GN TO EMP. 05 EMP-ID PIC 9(10). 05 EMP-SSN PIC 9(10). 0 05 EMP-BASIC PIC 9(8)V9(2). DB2 Guide Page 24 of 28 EXEC SQL ****************************************************************** EXEC SQL DECLARE SSS035.EDCL TA ( EMPID EMPNAME CHAR(20), SSN DECIMAL(10, 0), DOJ DATE, DOB DATE, ADDRESS CHAR(100)) END-EXEC. **** ******** * HOST VARIA **** 10 EV-EMPID PIC S9(9) USAGE COMP. 10 EV-EMPNAME PIC X(20). 10 EV-DOB PIC X(10). ****************************************************************** * DECLARATION OF TABLE SSS035.PDCL * ****************************************************************** EXEC SQL DECLARE SSS035.PDCL TABLE ( EMPID INTEGER NOT NULL, HRA DECIMAL(10, 2), ITAX DECIMAL(10, 2), GROSS DECIMAL(10, 2), NETSAL DECIMAL(10, 2)) END-EXEC. ****************************************************************** * HOST VARIABLE DECLARATION OF TABLE SSS035.PDCL * ****************************************************************** 01 DCLPDCL. 10 HV-EMPID PIC S9(9) USAGE COMP. 10 HV-BASIC PIC S9(8)V9(2) USAGE COMP-3. 10 HV-HRA PIC S9(8)V9(2) USAGE COMP-3. 10 HV-ITAX PIC S9(8)V9(2) USAGE COMP-3. 10 HV-GROSS PIC S9(8)V9(2) USAGE COMP-3. 10 HV-NETSAL PIC S9(8)V9(2) USAGE COMP-3. 01 WORK-AREAS. 05 WS-SQLCODE PIC -9(4). 05 WS-EMP-EOF PIC X VALUE 'N'. 88 EMP-EOF VALUE 'Y'. PROCEDURE DIVISION. 0000-MAIN-PARA. OPEN INPUT EMP-FILE. READ EMP-FILE AT END SET EMP-EOF TO TRUE END-READ IF EMP-EOF DB2 Guide Page 25 of 28 DISPLAY " EMPTY INPUT FILE......." END-IF PERFORM 1000-PROCESS-PARA UNTIL EMP-EOF CLOSE EMP-FILE GOBACK . 1000-PROCESS-PARA. 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 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.60 COMPUTE HV-ITAX = HV-BASIC * 0.20 COMPUTE HV-GROSS = HV-BASIC + HV-HRA COMPUTE HV-NETSAL = HV-GROSS - HV-ITAX ************************************************ * INSERT INTO EMP TABLE * ************************************************ INSERT INTO SSS035.EDCL(EMPID, EMPNAME, SSN, DOJ, DOB, ADDRESS) VALUES(:EV-EMPID, :EV-EMPNAME, :EV-SSN, :EV-DOJ, :EV-ADDRESS) END-EXEC IF SQLCODE = 0 ************************************************ * INSERT INTO PAY TABLE * ************************************************ INSERT INTO SSS035.PDCL(EMPID, BASIC, HRA, ITAX, GROSS, NETSAL) VALUES(:HV-EMPID, :HV-BASIC, :HV-HRA, :HV-ITAX, DB2 Guide Page 26 of 28 :HV-GROSS, :HV-NETSAL) END-EXEC IF SQLCODE = 0 DISPLAY " RECORDS INSERTED.............." 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. HOW TO HANDLE NULL VALUES Use null indicators. Syntax ... INTO: HOSTVAR [INDICATOR] : NULLIND otherwise DB 2 throws erro SQLCODE = -305. The picture clause of the null indicator variable S9(4) COMP. What does it mean if the null indicator has -1, 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, move -1 to the null indicator To insert a valid value, move 0 to the null indicator CURSOR COBOL program cannot handle more than one row at a time, Cursor is used to extra ct more than o from DB2 table or View. 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] DB2 Guide Page 27 of 28 Options WITH HOLD if you don t specify WITH HOLD cursor will be closed when you issue COMM IT DB2 the cursor and you will lose the current position of the cursor. If you want to retain the position of the CURSOR we need to specify this option. FOR FETCH ONLY/ FOR UPDATE OF FOR FETCH ONLY is used when you want to just read so DB2 will apply locks accordingly. FOR UPDATE OF is used when you want to update any column so that DB2 can apply a ppropriate This option is just for better locking its nothing to do with the result produce d by the cursor. Oy PTIMIZE FOR n ROWS If you inform BIND about a improve performance of the SQL statemeperformance as well so you should be OPEN the time of declare) EXEC SQL END-EXEC FETCH Fetch reads a row sequentially EXEC SQL END-EXEC CLOSE After all the EXEC SQL CLOSE cursor_name ND-EXEC E imple COBOL DB2 program which reads fro S D OPTIONS A ION Indi ADD Indicates that the named package does not ex already exis REPLACE DB2 Guide Page 28 of 28 In EXPLAIN package NO Explain information will not be captured. Explain tables will be populated with information about the chosen access plan a t prep/bind time for static statements and at run time for incremental bind stat ements. CS RR Spec ifies Repeatable Read Specifies RELEASE Indic DRDA precompile/bind option is not supp COM Release resou Release resources only when the application te