Вы находитесь на странице: 1из 70

SQL can be executed on Mainframe thru 1. SPUFI 2. QMF 3.

Embedded SQL

Queries on Mainframe thru QMF ( Query Management Facility )

Select Q

Select F6 for Query

Enter Query and RUN it by F2

Table contents : - BIZ.RDS_PC_AUDIT

EDIT Table by F8

Other Tool- platinum

platinum

EMBEDDED SQL
1. Embedding SQL Statements in the application program make the programming easy. 2. All Embedded SQL statements must be enclosed between delimiters. The delimiters for COBOL are EXEC SQL and END-EXEC.

3. These delimiters should be coded for each and every SQL statement and must start in column 12.
Example 1. EXEC SQL SELECT DEPTNO,DNAME FROM DEPT INTO :H-DEPTNO,:H-DNAME WHERE DEPTNO=:H-DEPTNO END-EXEC.

Example2:

EXEC SQL
SELECT COUNT(*) FROM EMP INTO :WS-COUNT WHERE DEPT = HRD

END-EXEC.

General Practice / Guidelines for embedded SQL which will make DB2 Application program perform better and will improve the maintainability 1. 2. 3. 4. 5. 6. Include DCLGEN copy book of all Tables referred in the Program. Include SQLCA, ( SQL Communication Area ) in WORKING-STORAGE section. Declare NULL indicator variables of PIC S9(4) COMP for handling NULL Value returns. Check the SQLCODE immediately after each SQL statement. Standardize error routine by having ERROR-HANDLING Paragraph. Depending on the SQLCODE , process respective action / paragraph.

7. Name DB2 programs , plans, packages and Variables cautiously.

Host Variable: is an area of storage allocated by the host language and referenced in the SQL statement. In COBOL ( Host Language ), these Variables ( Host variables ) must be defined in the DATA DIVISION of the program in the WORKING-STORAGE section or LINKAGE section. When you are using the Host variables in the SQL statements, prefix them with a colon eg. 01 WS-COUNT PIC 9(4). EXEC SQL SELECT FROM INTO WHERE END-EXEC. COUNT(*) EMPLOYEE :WS-COUNT DEPT = HRD

DCLGEN => is a DB2 Utility that produces host variables named as the SAME as the COLUMNS of Tables used in Program. => Prefix the column names with an abbreviated TABLE identifer.

DCLGEN
********************************************************** * DCLGEN TABLE (DEPT) ********************************************************** EXEC SQL DECLARE DEPT TABLE (DEPTNO CHAR(3) NOT NULL, DNAME VARCHAR(36) NOT NULL, LOCATION CHAR(16) ) END-EXEC ********************************************************** * COBOL DECLARATION FOR TABLE DEPT ********************************************************** 01 DCLDEPT 10 DEPTNO PIC X(3). 10 DNAME . 49 DNAME-LEN PIC S9(4) COMP. 49 DNAME-TEXT PIC X(36). 10 LOCATION PIC X(16). **********************************************************

SQLCA
An SQLCA is a set of variables that may be updated at the end of the execution of every SQL statement. A program that contains executable SQL statements may provide one SQLCA, but no more than one SQLCA to be present.

SQLCA
WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. ************************************** COBOL LAYAOUT OF EXPANDED SQLCA ************************************** 01 SQLCA. 05 SQLCAID PIC x(8). 05 SQLCABC PIC S9(9) COMP. 05 SQLCODE PIC S9(9) COMP. 05 SQLERRM. 49 SQLERRML PIC S9(4) COMP. 49 SQLERRMC PIC X(70). 05 SQLERRP OCCURS 6 TIMES 10 SQLERRD PIC S9(9) COMP. . .

Declare NULL indicator variables of of PIC S9(4) COMP for Handling NULL value returns. 01 DEPT-NULL-IND. 10 DNAME-IND PIC S9(4) COMP. 10 LOCATION -IND PIC S9(4) COMP. EXEC SQL SELECT DEPTNO,DNAME INTO :H-DEPTNO, :DNAME :DNAME-IND FROM DEPT WHERE DEPTNO = 10 END-EXEC. 1. If NULL value is returned then, :DNAME-IND will contain Negative Value. 2. If NOT NULL is returned then, :DNAME-IND will contain Positive number. 3. Always use NULL indicator Variable for Nullable Columns. If not it results in ERROR -305 SQLCODE and program will not give expected Value.

Writing a COBOL - DB2 Program. Let us assume we are writing a COBOL program to read EMPLOYEE table and get the details of employee with the name XXXXXXX. Let us go in step wise.. 1. EMPLOYEE Table.

We can use DB2 tool called DCLGEN to generate COBOL Eqvi., declaration for EMPLOYEE table, so that we can just include that copy book.

Press ENTER , You will get a message like " EXECUTION COMPLETE, MEMBER EMPLYEE ADDED "
Now member EMPLOYEE created. If you open the member , it looks like :-

If you want to access/update EMPLOYEE table, include this copybook in COBOL program as follows EXEC SQL INCLUDE EMPLOYEE END-EXEC.

DB2 CURSORS There are two types of embedded SQL SELECT statements. 1. Singleton SELECT - returns ONE row 2. Cursor SELECT -

Host Language programs operates only ONE row at a TIME. When SQL returns more than one row, the value of the first ROW is placed in the host variable and the DB2 issues an SQLCODE of -811. ( more than one row is returned from resultant set / query )
DB2 uses CURSOR to navigate through a set of rows returned by an embedded SQL SELECT statement. Cursor can be compared to POINTER. The Programmer Declares a cursor and defines the SQL statement for the cursor. Once the cursor is OPENED, rows are fetched from the cursor ONE ROW at a time and at the end CURSOR is CLOSED. 1. DECLARE 2. OPEN 3. FETCH 4. CLOSE

When CURSORs are used to process multiple rows, => the cursor is DECLAREd => OPENed and => the FETCH statement is coded in a loop that reads and processes each row and at the end that is when there are no more rows to be fetched, the FETCH statement returns a SQLCODE of +100 indicating no more rows. => Finally CLOSE the Cursor.

CURSOR = >is a mechanism to process query results in a tuple-oriented way. i.e, one record tuple at a time.
=> is useful when more than one row of a table to be processed. => A cursor basically is a pointer to a query result and is used to read attribute

values of selected tuples/ records into variables. => A cursor typically is used in combination with a loop construct such that each tuple read by the cursor can be processed individually. Cursor processing is done in several steps: 1. Define the rows you want to retrieve. This is called declaring the cursor. 2. Open the cursor. This activates the cursor and loads the data. Note that defining the cursor doesn't load data, opening the cursor does. 3. Fetch the data into host variables. 4. Close the cursor.

CURSOR A row-positioned cursor retrieves at most a single row at a time from the result table into host variables. At any point in time, the cursor is positioned on at most a single row. Cursor processing is done in several steps: 1. DECLARE 2. OPEN 3. FETCH 4. CLOSE CURSOR options specified along with DECLARE statements. 1. WITH HOLD and WITHOUT HOLD 2. WITH RETURN 3. WITH RELEASE

PROGRAMMING WITH CURSORS


WORKING-STORAGE SECTION. ... EXEC SQL DECLARE C1 CURSOR FOR SELECT DEPTNO,DNAME,LOC FROM DEPT WHERE DEPTNO=:H-DEPTNO END-EXEC. .. PROCEDURE DIVISION. .. . MOVE 10 TO H-DEPTNO

EXEC SQL OPEN C1 END-EXEC. IF SQLCODE<0 THEN PERFORM 9999-ERROR-PARA.

MOVE YES TO MORE-ROWS. PERFORM 200-PROCESS-DEPTS UNTIL MORE-ROWS=NO. EXEC SQL CLOSE C1 END-EXEC.
GOBACK. 200-PROCESS-DEPTS.

EXEC SQL FETCH C1 INTO :H-DEPTNO, :H-DNAME, :H-LOCATION END-EXEC.

IF SQLCODE<0 PERFORM 9999-ERROR-PARA. IF SQLCODE = +100 MOVE NO TO MORE-ROWS ELSE PERFORM FURTHER PROCESSING.

FETCH retrieves rows using a previously-created cursor. A cursor has an associated position, which is used by FETCH. The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result. When created, a cursor is positioned before the first row. After fetching some rows, the cursor is positioned on the row most recently retrieved. If FETCH runs off the end of the available rows then the cursor is left positioned after the last row, or before the first row if fetching backward. FETCH ALL or FETCH BACKWARD ALL will always leave the cursor positioned after the last row or before the first row.

The forms NEXT, PRIOR, FIRST, LAST, ABSOLUTE, RELATIVE fetch a single row after moving the cursor appropriately. If there is no such row, an empty result is returned, and the cursor is left positioned before the first row or after the last row as appropriate. The forms using FORWARD and BACKWARD retrieve the indicated number of rows moving in the forward or backward direction, leaving the cursor positioned on the last-returned row (or after/before all rows, if the count exceeds the number of rows available). RELATIVE 0, FORWARD 0, and BACKWARD 0 all request fetching the current row without moving the cursor, that is, re-fetching the most recently fetched row. This will succeed unless the cursor is positioned before the first row or after the last row; in which case, no row is returned.

CURSOR Example:

WITH HOLD option: If an application completes a unit of work by issuing a COMMIT statement, all open cursors, ( except those declared using the WITH HOLD option ) are automatically closed by the database manager. A cursor that is declared WITH HOLD maintains the resources it accesses across multiple units of work. If the unit of work ends with a COMMIT statement, open cursors defined WITH HOLD remain OPEN. The cursor is positioned before the next logical row of the result table. In addition, prepared statements referencing OPEN cursors defined WITH HOLD are retained.

WITH RELEASE option: When an application closes a cursor using the WITH RELEASE option, DB2(R) attempts to release all READ locks that the cursor still holds. The cursor will only continue to hold WRITE locks.

If the application closes the cursor without using the RELEASE option, the READ and WRITE locks will be released when the unit of work completes.

WITH RETURN option: This clause indicates that the cursor is intended for use as a result set from a procedure. WITH RETURN is relevant only if the DECLARE CURSOR statement is contained with the source code for a PROCEDURE. In other cases, the precompiler may accept the clause, but it has no effect. Within an SQL procedure, cursors declared using the WITH RETURN clause that are still open when the SQL procedure ends, define the result sets from the SQL procedure.

All other open cursors in an SQL procedure are closed when the SQL procedure ends.
Within an external procedure (one not defined using LANGUAGE SQL), the default for all cursors is WITH RETURN TO CALLER. Therefore, all cursors that are open when the procedure ends will be considered result sets.

Declaration for an insensitive scrollable row cursor EXEC SQL DECLARE C1 INSENSITIVE SCROLL CURSOR FOR SELECT DEPTNO, DEPTNAME, MGRNO FROM DSN8810.DEPT ORDER BY DEPTNO END-EXEC. Declaration for an sensitive STATIC scrollable row cursor EXEC SQL DECLARE C2 SENSITIVE STATIC SCROLL CURSOR FOR SELECT DEPTNO, DEPTNAME, MGRNO FROM DSN8810.DEPT ORDER BY DEPTNO END-EXEC. Declaration for an sensitive DYNAMIC scrollable row cursor EXEC SQL DECLARE C2 SENSITIVE DYNAMIC SCROLL CURSOR FOR SELECT DEPTNO, DEPTNAME, MGRNO FROM DSN8810.DEPT ORDER BY DEPTNO END-EXEC.

EXEC SQL DECLARE C1 CURSOR WITH ROWSET POSITIONING FOR SELECT EMPNO, LASTNAME, SALARY FROM DSN8810.EMP END-EXEC.

EXEC SQL FETCH NEXT ROWSET FROM C1 FOR 20 ROWS INTO :HVA-EMPNO, :HVA-LASTNAME, :HVA-SALARY :INDA-SALARY END-EXEC.

PROGRAM PREPARATION

COBOL-DB2 PROGRAM DSNHPC

PRECOMPILER

MODIFIED SOURCE

DBRM

BIND PACKAGE

COMPILER

BIND PLAN

PACKAGE

COMPILED SOURCE

PLAN
LINKAGE EDITOR - IEWL

DATA
LOAD MODULE

1.

DB2 s PRECOMPILER , Reads the source code ( COBOL-DB2 pgm ) and comments out the SQL statements and replaces them with CALLS to DB2. PRECOMPILER checks each SQL syntax errors and compares tables and columns named in statements against any SQL DECLARE TABLE statements in the program. OUTPUT OF PRECOMPILER
PRECOMPILER

MODIFIED SOURCE

DBRM

The MODIFIED SOURCE code that is produced by the precompiler must be compiled and link-edited.

PRECOMPILER: 1. The DB2 Application program contains COBOL code with SQL statements embedded on it. The COBOL compiler will not be able to recognize the SQL statements and will give compilation errors.
2. So before running the COBOL compiler, the SQL statements must be removed from SOURCE code.

3. Extracts all the SQL statements and places them in DBRM. 4. Places a timestamp token in the modified source and the DBRM to ensure that these two items are inextricably tied.

BINDING: The BIND command is a type of COMPILER for SQL statements. 1. Reads the SQL statements in the DBRM and checks the syntax of those statements. 2. Performs Authorization Validations. 3. Optimizes the SQL statements into efficient access paths. Two Types of BINDS: 1. BIND PLAN 2. BIND PACKAGE BIND PLAN accepts one or more DBRMs produced from previous DB2 precompilations. BIND PACKAGE command accepts a DBRM as input and produces a single package containing the optimized access path logic.

Link-Editing
MODIFIED SOURCE

After compilation , the Compiled source is linkEdited to an executable Load Module. The appropriate DB2 host language interface module also must be included in the Link-Edit step. The interface module is based on the environment in which the program will execute. The OUTPUT of the link-edit step is an executable load module, which can be run with a PLAN containing the programs DBRM or PACKAGE.

COMPILE and LINK EDIT

LOAD MODULE

Running a DB2 Program

Once the Link-edited Load Module and the DB2 PLANs are produced,
PLAN contains the ACCESS PATH specification for the SQL statements in program. LOADMODULE contains the executable machine instructions for the COBOL statements in the program. => Neither is executable without the Other.

PRECOMPILER

DBRM

BIND PACKAGE

BIND PLAN DBRM : Database Request Module

PACKAGE

A DBRM contains SQL statements extracted from the source program by the DB2 precompiler. DBRM is stored as the member of the Partitioned data set. DBRM is not stored in the DB2 Catalog or DIRECTORY. When a DBRM is bound to PLAN, all the SQL statements are placed in the SYSIBM.SYSSTMTDB2 catalog table. When a DBRM is bound to PACKAGE, all the SQL statements are placed into SYSIBM.SYSPACKSTMT catalog table.

PRECOMPILER

DBRM

BIND PACKAGE

PLAN

BIND PLAN

PACKAGE

A Plan is an executable module, containing the ACCESS PATH Logic provided by the DB2 Optimizer. PLAN can be composed of one or more DBRMs and PACKAGEs. PLANs are created by BIND command.

When a PLAN is bound DB2 reads the following Catalog tables.


SYSIBM.SYSUSERAUTH table is read only for BIND ADD. Information about the Plan is stored in the SYSIBM.SYSDBRM,SYSIBM.SYSPACKAUTH, SYSIBM.SYSPLAN, SYSIBM.SYSPLANAUTH, SYSIBM.SYSPLANDEP, SYSIBM.SYSPLSYSTEM, SYSIBM.SYSSSTMT and SYSIBM.SYSTABAUTH.

PRECOMPILER

DBRM

BIND PACKAGE

PACKAGE

BIND PLAN

PACKAGE

A PACKAGE contains a 1. LOCATION identifier 2. COLLECTION identifer 3. PACKAGE identifier. These 3 identifiers are used to uniquely identify the package. A PACKAGE is single BOUND DBRM with OPTIMIZED Access Path. PACKAGES can NEVER be directly executed. PACKAGES are executed ONLY, when the PLAN in which they are contained is executed. Information about the PACKAGE is stored in the SYSIBM.SYSPACKAGE, SYSIBM.SYSPACKAUTH, SYSIBM.SYSTABLES, SYSIBM.SYSTABLESPACE

The Executable form of the package is stored as a skeleton package table in the DB2 DIRECTORY in the SYSIBM.SPT01 table.

COLLECTION. A COLLECTION is a user-defined name ( 1 to 18 characters ) that the programmer must specify for every package. COLLECTION is a grouping of DB2 PACKAGEs. By specifying a different collection identifier for a PACKAGE the same DBRM can be bound to different packages.

This capability permits the programmer to use the same DBRM for different packages, enabling easy access to tables that have the same structure but different owners.

1. DCLGEN must be run before the PRECOMPILER. 2. PRECOMPILER must be run before the COBOL compiler and BIND. 3. BIND may be run between the PRECOMPILER and RUN steps. 4. LINK-EDIT may be run any time between the compile and RUN steps. The Separation of SOURCE and SQL may lead to inconsistency if you changed your program, Precompiled , compiled and link-edited it WITHOUT REBINDING the changed DBRM. Then Load module and Application Plan would be out of synch.

DB2 prevents this by putting TIMESTAMP on DBRM and TIMESTAMP on Modified Source.

PRECOMPILER DSNHPC

MODIFIED SOURCE TIMESTAMP A

DBRM TIMESTAMP A

COMPILE and LINK-Edit

BIND PLAN

LOAD MODULE TIMESTAMP A

Application PLAN TIMESTAMP A

TIMESTAMPs match ?
YES NO

RUN

-818 SQLCODE ABEND

The DB2 Precompiler - DSNHPC Eg. PGM=DSNHPC A pure COBOL program can compiled by IGYCRCTL
Eg. PGM=IGYCRCTL

LINK-EDIT by IEWL
Eg. PGM=IEWL

COBOL-DB2 COMPILE JCL

(1) - When we precompiled, precompiler will create the DBRM, it will be placed in the pds specified here.

( 2 ) - Location of COBOL-DB2 program

(3) - Needs to speficiy DCLGEN member locations

(4) - Needs to specify DCLGEN and COPYBOOK locations here

(5) - Load module location, load module will be created here. This Location needs to be given in RUN JCL.

(6) - Specify Location of DBRM and (7 ). BIND application

RUN JCL COBOL-DB2

SQLCODES
CODE 000 +100 +204 +551 -181 -301 -407 -811 -904 TYPE OF ERROR SUCCESSFUL EXECUTION NO ROWS FOUND THE NAMED OBJECT IS NOT DEFINED IN DB2. LACKS AUTHORITY TO PERFORM THE NAMED OPERATION ON THE NAMED DB2 OBJECT. NOT A VALID DATE,TIME OR TIMESTAMP VALUE. INVALID HOST VARIABLE DATATYPE. CAN NOT INSERT A NULL VALUE INTO COLUMN THAT IS DEFINED AS NOT NULL. EMBEDDED SELECT STATEMENT RETURNS MORE THAN ONE ROW , A CURSOR MUST BE USED. SPECIFIED RESOURCE IS NOT AVAILABLE. Example of DB2 SQL error: SQLCODE: -805, SQLSTATE: 51002, SQLERRMC: DSN8.FCPXP29.YSNT003Q.4742717A48444C74; RXTCS;04

DB2 CATALOG QUERY


1> TO VIEW THE STRUCTURE OF THE TABLE; SELECT * FROM SYSIBM.SYSCOLUMNS WHERE TBNAME=DEPT; 2> TO FIND OUT THE TABLE THAT CONTAINS FOREIGNKEY COLUMNS; SELECT * FROM SYSIBM.SYSFOREIGNKEYS WHERE TBNAME=DEPT; 3> TO FIND OUT INDEXES ON TABLE ; SELECT * FROM SYSIBM.SYSINDEXES WHERE TBNAME=DEPT; 4> TO FIND OUT WHICH TABLES CAN BE ACCESSED BY WHOM; SELECT * FROM SYSIBM.SYSTABAUTH; 5> TO LIST ALL THE TABLES OF THE DATABASE; SELECT * FROM SYSIBM.SYSTABLES ;

Refresh
1>

THE MAXIMUM NUMBER OF COLUMNS A DB2 TABLE CAN CONTAIN : 224

2> SKELETON CURSOR TABLE(SKCT):

THE EXECUTABLE FORM SQL STATEMENT. THIS IS STORED IN SYSIBM.SCT02 TABLE.


3> THE MAXIMUM LENGTH OF SQLCA: 136 BYTES. 4> WHAT IS THE MAXIMUM NUMBER OF TABLES THAT CAN BE JOINED: 15 (FIFTEEN).

Вам также может понравиться