Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 78

DB2 Day 4

Objectives

 Sub Queries
 Views, Alias and Synonym
 Embedded SQL - Communicate with DB2
 Describe set processing and handling cursors
Objectives

 Describe the SQLCA and how to interpret


messages from DB2
 List the steps involved in preparing the program for
execution
 Explain the differences between static and dynamic
SQL
SUBQUERIES

 Are nested SELECT queries

 Can be very useful when rows are needed to be


selected from a table with a condition that depends
on the data in the table itself.

 Often referred to as a sub select or inner select


SUBQUERIES

SELECT col1,col2,…,col N
FROM table
WHERE column =
(SELECT column1
FROM table
WHERE condition );
SUBQUERIES

 Case 1: To find the employee name who earns the


minimum salary, two steps are needed.

 STEP1: Find the minimum salary


SELECT MIN(SAL) FROM EMP;

 STEP2: Find the employee name who earns


minimum salary
SELECT ENAME FROM EMP
WHERE SAL = Lowest salary which is
unknown;
SUB QUERIES

 The above two steps can be combined through a


sub query:

SELECT ENAME
FROM EMP
WHERE SAL =
( SELECT MIN(SAL)
FROM EMP );
First it selects
MINIMUM SALRY
then employee
FNAME
View

 View is like a window through which data and


tables can be viewed or changed.
 Derived from another table or another view which
stores data physically.
 Stored as a SELECT statement only-it is a virtual
table that does not physically exist in its own right,
but appears to the user as if it does.
View

 A view has no data it manipulates data in the


underlying base table
 Allows the same data to be seen by different
users in different views.
Syntax:
CREATE VIEW <view name>
AS
SELECT col1, col2
FROM <table name>
WHERE <col name>
=value;
CREATE VIEW EMPDP
AS SELECT EMPNO, FNAME
FROM EMPS WHERE DEPTNO = ‘D002’;
Virtual table
View EMPDP
is created
with only two
fields
Query to get
the view
content
When we change the
content of the base
table, the latest
information will
appear in the VIEW

After changing the Base


Table, if we look into base
table the changes will
appear
DB2 Privileges

 IMPLICIT – Automatic privileges for CREATOR


of object

 EXPLICIT – Specific privilege provided by


GRANT and REVOKE SQL Statement
Implicit Privileges on Table

 All DML
 ALTER and DROP of table
 CREATE and DROP indexes
 References – referential constraints
 Run certain DB2 utilities
DCL (Data Control Language)

 Explicit privileges can be given to the user by


the DCL Statements
 GRANT
 REVOKE
Explicit privileges on Table

 Syntax
 GRANT <operation> On <Object Type> < object name>
This query will allow
TO <user id> / PUBLIC; SELECT operation
on EMPS & DEPTS
table for user called
DAVIN15 &
TRNR007

This query will


allow SELECT
operation on
EMPS DEPTS
table for all the
users
Example:
 GRANT SELECT, INSERT, UPADATE,DELETE ON
TABLE EMPS
TO CMAP112, CPRJ101

ALL means
 Grant ALL ON TABLE EMPS TO USER1 all the
operations

 GRANT SELECT ON TABLE EMP TO PUBLIC


REVOKE Privileges

 Syntax
 REVOKE <operations> ON <Object Type> <Object
name>
From user-id Now this revokes the
privilege from
TRNR007
He can’t perform
select from EMPS
table
Removing privileges on Table from the user

 REVOKE SELECT
ON TABLE EMP,DEPTS FROM CMAP112;

 REVOKE ALL ON TABLE EMP FROM USER1;

 REVOKE ALL ON TABLE EMP FROM PUBLIC;


Union

 The UNION operation combines two sets of


rows into a single set composed of all the rows
in either or both the original sets.
Rules for Union

 The two sets must contain the same number of


columns

 Each column in the first set must be either of the


same data type as the corresponding column of the
second set or convertible to the same data type as
the corresponding column of the second set
Example
EMPPER - Table EMPTEP - Table

EMPNO EMPNO

ENAME ENAME

Let us consider the two


table with similar
structure
Created &
Inserted
values for
EMPPER
Created &
Inserted
values for
EMPTEP
Now
EMPPER
table has 6
records
EMPTEP
has 3 records
Syntax

SELECT * FROM < table1>


UNION SELECT * FROM <table2>

UNION eliminates
duplicates .
Out off 6+3 = 9
records , 7 records
is displayed
Syntax

SELECT * FROM < table1>


UNION ALL SELECT * FROM <table2>

UNION ALL will


results in
combination of
both the table
Synonym

 An alternative name for a table or view.

 Mainly to hide qualifier of a table

 Can be accessible only by creator

 It is dropped when table / table space is dropped

 Synonyms can only be used to refer to objects at the


subsystem in which the synonym is defined.
Syntax
CREATE SYNONYM <syn name> FOR DAVIN5.EMP
<user id > . <table name>; S can be
referred as
SYEMPS
If table is
deleted, then
synonym also
will get deleted
EMBEDDED SQL Programming

Static SQL
Program Preparation.
Embedded SQL programming

 So far we have learnt how to query the data base


objects with SPUFI & QMF

 To perform DDL, DML DCL operations with the


application program like COBOL, we need to embed
SQL code inside application programs.

 SQL codes can also embedded with other


programming languages such as PL/1 & Assembler
SQL Communication Area

 Each time a DB2-COBOL program executes DB2


passes information about success or failure
which is done by SQLCA.
 SQLCODE field tells result of last executed SQL
request. This should be
included in
WORKING-
STORAGE
EXEC SQL
SECTION.
INCLUDE SQLCA The field
SQLCODE is used
END-EXEC in program to know
about the result of
execution
SQL Execution validation

 SQLCA – is a valuable problem diagnosis tool for


an Embedded SQL program.

 It contains the following messages like


 SQLCODE

 SQLWARNING
 SQLERROR
 SQLSTATE
SQL Codes
SQLCODE value
can be 0, positive
value or negative
SQLCODE MEANING values with
following meaning
0 Execution was successful
>0 Execution was successful with warning ( + ve )

<0 Execution was not successful ( - ve)


100 Indicates no records found
DCLGEN
DCLGEN should
be included in
WORKING-
STORAGE
 Issued for a single table SECTION

 Prepares the structure of the table in a COBOL


copybook
 The copybook contains a ‘SQL DECLARE
TABLE’ statement along with a working storage
host variable definition for the table DCLGEN.
Create one PDS for
Use naming
convention as
userid.DB2.DCLGEN
with FB, 80 RECSIZE
& 800 BLKSIZE
Host Variables

 Definitions for fields that can be used to receive


data which
 DB2 returns to program

 DB2 can use to update tables

 Called host variables because they reside in


storage owned by host program

 Normally use Working Storage variables as host


variables.
 Referenced in an SQL statement

 When using them in SQL statements they should


be prefixed by a colon(:)

 When same variable is used outside the SQL


statement , do not use colon(:).
Host Variable Declaration
DB2 field variables
will be converted
into equivalent
COBOL data type as
shown in the table
by DCLGEN
Host Variable Declaration

DB2 DATE, TIME


& TMESTAMP will
be converted into
equivalent COBOL
data type as shown
in the table by
DCLGEN
To create
DCLGEN,
GOTO option 8
then choose
option 2
Give the table for which
declaration is required You have created one
here. In our case EMPV PDS for DCLGEN.
is table name Give that name and
member name can be
any thing . Better keep
the same name as that of
table name
When you are doing first
time, it will result in Member
added.
This will result in COBOL Subsequent times the same
declarations of the table table and member name is
EMPV in DCLGEN PDS . used, it will show Member
Let us open and check the replaced
member which is added.
See the data type
conversion and
declaration

This declaration is used by


program
Simple EMBEDDED SQL code - Selecting one
record

Create the required PDS as follows:

 For source code - USERID.DEV.SOURCE


 For DBRMLIB - USERID.DEV. DBRMLIB
 For Load module - USERID.DEV.LOAD
 This should be RECFM – U, RECLEN – 80,
BLKSIZE - 800
 For DCLGEN - USERID.DEV.COPYLIB(already
discussed about DCLGEN)
 Keep ready with four PDS, this we need to refer in JCL
Embedded SQL

Embedded SQL statements

They are delimited with


EXEC SQL
[………]
END-EXEC.

Normally the embedded SQL statements contain


the host variables coded with the INTO clause of
the SELECT statement.
Embedded SQL

E.g.
Record
EXEC SQL retrieved
from table
SELECT EMPNO, ENAME will be hold
in host
INTO :HV- variable
EMPNO, :HV-ENAME
FROM EMPS
WHERE EMPNO = :HV-EMPNO
END-EXEC.
Include Table
EMPPER and
SQLCA to get result
of DB2 transaction

SCODE is signed
variable to get
SQLCODE
SELECT col1,col2…
INTO :host-var Let us select record
FROM table-name for EMPNO 10014
WHERE Hence move this
value to variable Slight variation in
colname= :host-var Syntax

Check select
operation is
success / not with
SQLCODE = 0
else get the
information about
status with
SQLCODE When SQLCODE is 0,
display the retrieved record
else display SQLCODE
 The procedure used to compile embedded SQL is
DSNHCOB1
 The JCL as follows :
 JCL is in the forms of two steps
Give the Name of Procedure
name of library in JCLLIB, Give the
Source PDS where you have name of
in DSNHCOB procedure DBRMLIB
PC.SYSIN PDS in
PC.DBRMLI
B
Give the
name of
DCLGEN
PDS in
PC.SYSLI
B

Give the name of


Load Module PDS in
LKED.SYSLMOD –
PDS with U format
STEP2Sub
of JCL
system
ID
DSN2

PLAN is
USERID
+P

Program
Name (Load
Module)

DBRM
Library
Where
DBRM’s
Do all these stored
changes &
Submit
RUN JCL

Give your Load


library & submit
If JCL results in
error , go through
the steps to
resolve.
Give S in
SYSOUT
to see the
output
One
record
with
EMPNO
10014
Now same code ,
moving 11114 to
EMPNO.
Let us see what
happens
In SYSOUT,
SQL CODE
displays like
junk, not in
readable
format

Change the code to get Error


Description along with
SQLCODE
In format
Use CALL
Error
Descriptor SQLCA is input
Program ERR-MSG and
DSNITIAR ERR-LRECL is
To get error output
message For
description DSNITIAR
SQLCODE
Error
is
message
10{ means
description
100
Pre-compilation & Execution steps

 Let us discuss insights in Pre-compilation,


DBRM, BIND and execution process
Source Program

DB2 Pre-
Modified Source compiler
Non-SQL SQL

DBRM
Compilation

DB2 Catalog Bind Package Bind Plan


Object Program

Plan
Link Edit

Load Module
Load Module Application plan

Execute
Pre-compilation

 Program used: DSNHPC


 INPUT  EMBEDDED SQL PROGRAM
 OUTPUT  Modified source CODE
 Database Request Module
DB2 Pre-compilation

• INCLUDES SQLCA

• Separates SQL from Non-SQL and places the


SQL statements in Database Request Module

• Replaces the SQL statements in the source


program with COBOL Equivalent CALL
statements

• Checks for some errors

• Does not access DB2 catalog

• Timestamps both outputs


Data Base Request Module (DBRM)

 DBRM is a module containing SQL statements


from the source program, which have been
extracted by the DB2 Pre-compiler.

 The module is stored as a member of a


partitioned data set.

 The DBRM is used as input to the BIND process


BIND Comments

• Checks for errors, using DB2 catalog


• Checks authorization or privileges
• Optimizes the query(done by DB2 Optimizer)
• Develops BEST Access strategy for each
statement
• Stores strategies as PLAN/PACKAGE (reusable
without repeating bind)
Bind

 INPUT  DBRM LIB produced in pre-compiler


step
 OUTPUT  PLAN / PACKAGE
 Function: Reads the SQL statements from
DBRMs and produces a mechanism to access
data from tables.
BIND Comments

 Two types of Binds - BIND PLAN, BIND PACKAGE


 BIND PACKAGE accepts a DBRM as input and
produces a SINGLE package.
 A package is not executable. Packages should be
bound into a plan before executing.
 BIND PLAN accepts many DBRMs or PACKAGES
and produces the executable logic giving the access
path to DB2 data.
Get familiarize with few SQLCODES

 -104 - illegal use of key word


 -199 - Illegal use of KEYWORD. Token-list
was expected .
 -204 - NAME is an undefined Name.
 -205 - COLUMN-NAME is not a Column of
Table TABLE-NAME.
 -206 - COLUMN-NAME is not a Column of a
Inserted Table, Update Table, or any Table
identified in a FROM Clause.
Get familiarize with few SQLCODES

 -117 - The number of insert values is not the


same as the number of object columns

 -304 - The value inserted is out of range

 -305 - The null value cannot be assigned to


output host variable number because no
indicator variable is specified
Get familiarize with few SQLCODES

 -805 - Program not found in the PLAN

 -818 - The pre-compiler generated Timestamp


X in the load module is different from the Bind
Timestamp Y built from the DBRM.

 Answer: Compile and Bind must have the same


Timestamp. Rebind or Recompile and then
Rebind. Also note down the SQLCODE, you have
encountered during your lab session.
Use SPUFI , so that you may get
SQLCODE and Error Description also.
 Similarly try to code all DDL & DML queries in
Application program and execute

 Get hands on embedded programming


Exception Handling

 EXEC SQL
WHENEVER SQLERROR GOTO <Err-Para>
END-EXEC.

 EXEC SQL
WHENEVER SQLWARNING GOTO
<Warning-Para>
END-EXEC.

 EXEC SQL
WHENEVER NOT FOUND CONTINUE
END-EXEC.

You might also like