Академический Документы
Профессиональный Документы
Культура Документы
*********** IMP ********* the temporary table is created only when when some SQL
operation is done on it like( select,update)
4) one more way to create a temporary table is to use the command declare global temporary
table name, for this a temporary DB and temporary TS have to be created as follows:
CREATE DATABASE DTTDB AS TEMP;
CREATE TABLESPACE DTTTS IN DTTDB SEGSIZE 4;
The second kind of temporary table exists only until the session exists
VIEWS
•It is a logical derivation of a table from other table/tables. A View does not exist in its own
right.
•They provide a certain amount if logical independence
•They allow the same data to be seen by different users in different ways
•In DB2 a view that is to accept a update must be derived from a single base table
Aliases
•Mean ‘another name’ for the table.
•Aliases are used basically for accessing remote tables (in distributed data processing), which
add a location prefix to their names.
•Using aliases creates a shorter name.
Synonym
•Also means another name for the table, but is private to the user who created it.
Syntax:
CREATE VIEW <Viewname> (<columns>)
AS Subquery (Subquery - SELECT FROM other Table(s))
CREATE ALIAS <Aliasname> FOR <Tablename>
CREATE SYNONYM <Synonymname> FOR <Tablename>
Embedded SQL
•It is like the file I/O
•Normally the embedded SQL statements contain the host variables coded with the INTO clause
of the SELECT statement.
•They are delimited with EXEC SQL ...... END EXEC.
•E.g. EXEC SQL
SELECT Empno, Empname INTO :H-empno, :H-empname
FROM EMPLOYEE
WHERE empno = 1001
END EXEC.
CURSOR:
DECLARE:
EXEC SQL
OPEN:
EXEC SQL
OPEN EMPCUR
END-EXEC.
FETCH:
EXEC SQL
FETCH EMPCUR
INTO :Empno, :Empname, :Dept, :Job
END-EXEC.
CLOSE
E.g. - For the Close statement
EXEC SQL
CLOSE EMPCUR
END EXEC.
When you update a row or delete a row from table using cursor, Data integrity is maintained
because the current row is locked for usage.
UPDATE
E.g. - For the Update statement using cursors
EXEC SQL
UPDATE EMP
Set Job = :New-job
WHERE current of EMPCUR
END EXEC.
DELETE
E.g. - For the Delete statement using cursors
EXEC SQL
DELETE FROM EMP
WHERE current of EMPCUR
END EXEC.
Program preparation:
PRECOMPILE ---> separates all the DB2 code and writes it in a DBRM and Modified source
code and DBRM are tagged with
•Searches all the SQL statements and DB2 related INCLUDE members and comments out every
SQL statement in the program
•The SQL statements are replaced by a CALL to the DB2 runtime interface module, along with
parameters.
•All SQL statements are extracted and put in a Database Request Module (DBRM)
•Places a timestamp in the modified source and the DBRM so that these are tied. If there is
a mismatch in this a runtime error of ‘-818‘, timestamp mismatch occurs
•All DB2 related INCLUDE statements must be placed between EXEC SQL & END EXEC
keywords for the precompiler to recognize them
EXEC SQL
SELECT LASTNAME, WORKDEPT
INTO :CBLNAME, :CBLDEPT
FROM DSN8810.EMP
FETCH FIRST 1 ROW ONLY
END-EXEC.
Using both table column and host variable in the same SQL statement:
MOVE 4476 TO RAISE.
MOVE ’000220’ TO PERSON.
EXEC SQL
SELECT EMPNO, LASTNAME, SALARY, :RAISE, SALARY + :RAISE
INTO :EMP-NUM, :PERSON-NAME, :EMP-SAL, :EMP-RAISE, :EMP-TTL
FROM DSN8810.EMP
WHERE EMPNO = :PERSON END-EXEC.
The following results have column headings that represent the names of the host variables:
EMP-NUM PERSON-NAME EMP-SAL EMP-RAISE EMP-TTL
======= =========== ======= ========= =======
000220 LUTZ 29840 4476 34316
Inserting Data:
EXEC SQL
INSERT INTO DSN8810.ACT
VALUES (:HV-ACTNO, :HV-ACTKWD, :HV-ACTDESC)
END-EXEC.
EXEC SQL
UPDATE DSN8810.EMP
SET PHONENO = :NEWPHONE:PHONEIND
WHERE EMPNO = :EMPID
END-EXEC.
Move the whole row into a group that has the host variables as elementary items
If you want to avoid listing host variables, you can substitute the name of a structure, say
:PEMP, that contains :EMPNO, :FIRSTNME, :MIDINIT, :LASTNAME, and :WORKDEPT. The
example then reads:
EXEC SQL
SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT
INTO :PEMP FROM DSN8810.VEMP
WHERE EMPNO = :EMPID
END-EXEC.
--> Each and every cursor is associated with a table, multiple tables require multiple cursors
to access them
--> If SQLCODE = 100 means that end-of-table is reached
--> Do not mention the host variables with the SELECT clause when you have to return
multiple rows. So for this reason the FETCH statement is important when CURSOR's are
used. Only after FETCH statement is executed with host variables only then the rows are
retrieved into the table.
Create Cursor:
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, SALARY FROM DSN8810.EMP X
WHERE EXISTS
(SELECT * FROM DSN8810.PROJ Y WHERE X.EMPNO=Y.RESPEMP AND
Y.PROJNO=:GOODPROJ)
FOR UPDATE OF SALARY;
Fetch rows:
EXEC SQL
FETCH C1 INTO :HV-EMPNO, :HV-FIRSTNME, :HV-MIDINIT, :HV-LASTNAME, :HV-SALARY
:IND-SALARY
END-EXEC.
Positioned Update:
If FOR UPDATE is mentioned in the CURSOR DECLARE statement then positioned update
can be done as follows;
EXEC SQL
UPDATE DSN8810.EMP
SET SALARY = 50000
WHERE CURRENT OF C1
END-EXEC.
Positioned DELETE:
Cursor CLOSE:
********* ---> A cursor created with rowset positioning can fetch multiple rows
at a time:
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.
CASE statements:
Example 1 (simple-when-clause): Assume that in the EMPLOYEE table the first character of
a department number represents the division in the organization. Use a CASE expression to
list the full name of the division to which each employee belongs.
SELECT EMPNO, LASTNAME,
CASE SUBSTR(WORKDEPT,1,1)
WHEN 'A' THEN 'Administration'
WHEN 'B' THEN 'Human Resources'
WHEN 'C' THEN 'Design'
WHEN 'D' THEN 'Operations'
END
FROM EMPLOYEE;
Example 2 (searched-when-clause): You can also use a CASE expression to avoid "division
by zero" errors. From the EMPLOYEE table, find all employees who earn more than 25
percent of their income from commission, but who are not fully paid on commission:
SELECT EMPNO, WORKDEPT, SALARY+COMM FROM EMPLOYEE
WHERE (CASE WHEN SALARY=0 THEN 0
ELSE COMM/(SALARY+COMM)
END) > 0.25;
Example 3 (searched-when-clause): You can use a CASE expression to avoid "division by
zero" errors in another way. The following queries show an accumulation or summing
operation. In the first query, DB2® performs the division before performing the CASE
statement and an error occurs along with the results.
SELECT REF_ID,PAYMT_PAST_DUE_CT,
CASE
WHEN PAYMT_PAST_DUE_CT=0 THEN 0
WHEN PAYMT_PAST_DUE_CT>0 THEN
SUM(BAL_AMT/PAYMT_PAST_DUE_CT)
END
FROM PAY_TABLE
GROUP BY REF_ID,PAYMT_PAST_DUE_CT; However, if the CASE expression is included in the
SUM aggregate function, the CASE expression would prevent the errors. In the following
query, the CASE expression screens out the unwanted division because the CASE operation
performed before the division.
is
SELECT REF_ID,PAYMT_PAST_DUE_CT,
SUM(CASE
WHEN PAYMT_PAST_DUE_CT=0 THEN 0
WHEN PAYMT_PAST_DUE_CT>0 THEN
BAL_AMT/PAYMT_PAST_DUE_CT
END)
FROM PAY_TABLE
GROUP BY REF_ID,PAYMT_PAST_DUE_CT;
Example 4: This example shows how to group the results of a query by a CASE expression
without having to re-type the expression. Using the sample employee table, find the
maximum, minimum, and average salary. Instead of finding these values for each
department, assume that you want to combine some departments into the same group.
SELECT CASE_DEPT,MAX(SALARY),MIN(SALARY),AVG(SALARY)
FROM (SELECT SALARY,CASE WHEN WORKDEPT = 'A00' OR WORKDEPT = 'E21'
THEN 'A00_E21'
WHEN WORKDEPT = 'D11' OR WORKDEPT = 'E11'
THEN 'D11_E11'
ELSE WORKDEPT
END AS CASE_DEPT
FROM DSN8910.EMP) X
GROUP BY CASE_DEPT;
DB2 PLAN/PACKAGE:
REBIND PACKAGE:
REBIND PACKAGE (LEDGER.*) REBIND PACKAGE (LEDGER.*.(*))
REBIND PLAN:
Example: Rebinds PLANA and changes the package list:
REBIND PLAN(PLANA) PKLIST(GROUP1.*) MEMBER(ABC)
Example: Rebinds the plan and drops the entire package list:
REBIND PLAN(PLANA) NOPKLIST
CONCURRENCY/LOCKS:
LOCKS:
khbkh
Definition: Concurrency is the ability of more than one application process to access the
same data at essentially the same time.
Example: An application for order entry is used by many transactions simultaneously. Each
transaction makes inserts in tables of invoices and invoice items, reads a table of data about
customers, and reads and updates data about items on hand. Two operations on the same
data, by two simultaneous transactions, might be separated only by microseconds. To the
users, the operations appear concurrent.
Lost updates. Without concurrency control, two processes, A and B, might both read the
same row from the database, and both calculate new values for one of its columns, based
on what they read. If A updates the row with its new value, and then B updates the same
row, A’s update is lost.
Access to uncommitted data. Also without concurrency control, process A might update a
value in the database, and process B might read that value before it was committed. Then,
if A’s value is not later committed, but backed out, B’s calculations are based on
uncommitted (and presumably incorrect) data.
Unrepeatable reads. Some processes require the following sequence of events: A reads a
row from the database and then goes on to process other SQL requests. Later, A reads the
first row again and must find the same values it read the first time. Without control, process
B could have changed the row between the two read operations.
Read stability: same a RR but the difference is no one can modify the the row or page but
transactions can insert data.
If there is no requirement that same number of rows have to fetched when the transaction
is repeated on the table, RS can be used . Otherwise RR has to be used
Uncommited READ:
only relates to FETCH and SELECT
Helps you read uncomitted changes in the table.
Best for static tables, data retrieval is very fast
http://db2portal.blogspot.com/2009/06/know-your-isolation-levels.html
BIND options:
Acquire/Release:
RELEASE(COMMIT), RELEASE(DEALLOCATE)
deallocate is useful db2 applications where the sql statements make a lot of updates are
made to the table, that is when there are many instances of commit. Because if COMMIT
happens the lock is not released
If release(commit), is used lock is released every time after an update is made to the table
ACQUIRE(ALLOCATE): means the lock is acquired when the plan is allocated. That means
when the application starts all the tables, table spaces, partions are locked
ACQUIRE(USE) : means the lock is acquired when the SPECIFIC partition/table space/table
are accessed
Interview Questions:
Q7) After a table is defined, can columns be removed?
NO
Q65) How would you find out the total number of rows in a table? - GS
A65) Use SELECT COUNT(*) ...
TWO PHASE COMMIT: phase one: all the particpants are asked about their job, responses
are collected in this phase only
PHASE 2 if everybody says ok then commit, else rollback
Q6) What information is used as input to the bind process?
A6) The database request module produced during the pre-compile. The
SYSIBM.SYSSTMT table of the
DB2 catalog
DB2 DBA:
NUMPARTS2 (1 to 254)
(part1...)
(PART2...)
When a table having referential integrity is altered, the table space is put in check pending
status.
So ideally a parent table must be update before a child table is updated
DELETING A PLAN
Q24) What will the FREE command do to a plan?
A24) It will drop(delete) that existing plan.
DBRM: SYSIBM.SYSSTMT
PLAN: SYSIBM.SYSPLANS
Q36) What is the format (internal layout) of “TIMESTAMP”?
A36) This is a seven part value that consists of a date (yymmdd) and time(hhmmss and
microseconds).
Lets say SQL query is accessing 500 rows but requires only 10 rows from that for the use
RR-500
RS-10
CS-1
UR-none(read only)
Types of Locks:
Intent none:(Read only)
Lock Owner can only read the data, cannot modify
Applied on the table space/table
Shared/Exclusive/Update
CURSOR DELCARED WITH HOLD OPTION is not closed after a commit; explicit
close is required to close the cursor
Q54) What is the physical storage length of each of the following DB2 data types: DATE,
TIME,
TIMESTAMP?
A54) DATE: 4bytes
TIME: 3bytes
TIMESTAMP: 10bytes
Q55) What is the COBOL picture clause of the following DB2 data types: DATE, TIME,
TIMESTAMP?
A55) DATE: PIC X(10)
TIME : PIC X(08)
TIMESTAMP: PIC X(26)
Q65) How can you quickly find out the number of rows updated after an update statement?
A65) Check the value stored in SQLERRD(3).
PLAN EXECUTION:
DSN SYSTEM(DB2T)
RUN PROG(TESTPROG) PLAN(TESTPLAN)
END
PACKAGE parameters.
BIND PACKAGE(RR16388.TEST)
VERSION(TEST)
BIND PACKAGE(RR16388.PROD)
VERSION(PROD)
1) What is happening above is that same package has two versions, One being TEST and
the other PROD. Just used to maintain different regions. Next important thing is
COLLECTION ID. Collection ID is the HLQ of the package name.
BIND PLAN(PLANNAME)
PKLIST(RR16388.*)
2) All the packages with collection ID "RR16388" are bound into a PLAN
3) SQLERROR(CONTINUE|NOPACKAGE) : If there is an SQL error create a PACKAGE,
NOERROR
BIND PARAMETERS:
3) ISOLATION LEVEL(CS|RR|RS|UR)
4) ACTION(REPLACE) REPLACE is default replace the PLAN with the same name
5) ACQUIRE(ALLOCATE|USE) RELEASE(COMMIT|DEALLOCATE)
6) VALIDATE(RUN|BIND): Validate for PACKAGE not found and privilege issues during RUN
time iF RUN is mention, Else throw error message during the bind process
SQL CODES:
SQLCODE
The SQLCODE field contains the SQL return code. The code can be zero (0), negative or
positive.
0 means successful execution.
0 Successful
[edit] Negative values (Errors)
Null Indicators:
While select, If you doubt that the returned value might be null use a null indicator.
While update if you want to move null values then pass -1 into the null indicator and then
update/insert the table
******IMP*** while update , if you set the db2 field to a value that is stored in the host
variable and for example assume that host variable does have some value and if the
respective null indicator has -1 in it then the value in the host variable will not be inserted,
it will be set to NULL
S9(4) USAGE COMP means --> Small int as it occupies two bytes
Bufferpool: When DB2 tables are picked up from the disk to the Main memory The area of
Main memory that will be used by the DB2 tables is bufferpool
ALTER TABLE:
ALTER TABLE IBMGRP.ALTER ALTER COLUMN NAME SET DATA TYPE VARCHAR(100);
Now, suppose a user tries to insert a record into this view that has a RESPONSE_TIME value
of 6.
The insert operation will fail because the record violates the view’s definition. Had the view
not
been created with the WITH CHECK OPTION clause, the insert operation would have been
successful,
even though the new record would not be visible to the view that was used to add it.
SELECT <DISTINCT>
[* | [Expression] <<AS> [NewColumnName]> ,...]
FROM [[TableName] | [ViewName]
<<AS> [CorrelationName]> ,...]
<WhereClause>
<GroupByClause>
<HavingClause>
<OrderByClause>
<FetchFirstClause>
Order of execution:
· The DISTINCT clause
· The FROM clause
· The WHERE clause
· The GROUP BY clause
· The HAVING clause
· The ORDER BY clause
· The FETCH FIRST clause
Relational predicates
· < (Less than)
· > (Greater than)
· <= (Less than or equal to)
· >= (Greater than or equal to)
· = (Equal to)
· <> (Not equal to)
· NOT (Negation)
BETWEEN:
IN predicate:
SELECT LASTNAME, WORKDEPT FROM EMPLOYEES
WHERE WORKDEPT IN (SELECT DEPTNO FROM DEPARTMENTS
WHERE DEPTNAME = ‘OPERATIONS’ OR
DEPTNO = ‘SOFTWARE SUPPORT’)
AGGREGATE FUNCTION:
When MAX,MIN,SUM,AVG,COUNT(*) are used, the rows having null values are discarded.
FOr example:
MyTable
ID Name Amount
1 John 37
2 Jack NULL
3 Jim 5
4 Joe 12
5 Josh NULL
When avg(amount) is asked then DB2 will consider only 37+5+12/3 not (37+NULL + 5+
NULL+ 12)/5
Having Clause:
SELECT DEPTNAME, AVG(SALARY) AS AVG_SALARY
FROM DEPARTMENT D, EMPLOYEES E
WHERE E.WORKDEPT = D.DEPTNO
GROUP BY DEPTNAME
HAVING AVG(SALARY) > 30000.00
Hi
Union Vs Union all:
Union will return combined result of two different queries , Any duplicates will be eliminated,
Union All will not eliminate duplicates
Types of Locks:
The above two locks are only the ones which can get a lock at row level or page level
Intent share : Lock is obtained at a row or page level. other application ./ user can update
other rows
Share: Everybody can read the rows in table but nobody can update the table
Update: For the application to update any data , lock has to be promoted to X
DB2 FAq's:
http://muraliwebworld.com/db2.aspx
If SELECT statement has to be used within DECLARE CURSOR, there is no other place where
in we can retrieve rows . Declare cursor can be used with UPDATE/DELETE (In the sence
select statement should be there with UPDATE / DELETE statements like FOR UPDATE OF)
INSERT is not allowed with DECLARE CURSOR