Sie sind auf Seite 1von 21

Table

Name
Schema Purpose
SYSTABLES SYSIBM Information about all tables in the database
SYSINDEXES SYSIBM Information about the indexes on all tables
SYSVIEWS SYSIBM Information on all views in the database
select name, creator
from sysibm.systables
where creator = 'FUZZY'

DataDefinitionLanguage(
DDL
)

Create,AlterandDrop

DataManipulationLanguage(
DML
)

Select,Insert,UpdateandDelete

DataControlLanguage(
DCL
)

GrantandRevoke

Allthetablesarecreatedintablespaces.
TablespacesresideonESDSorLDS

Creationoftemporarytables:

1)
CREATEGLOBALTEMPORARYTABLE
TEMPPROD(SERIALCHAR(8)NOT
NULL,DESCRIPTIONVARCHAR(60)NOTNULL,MFGCOSTDECIMAL(8,2),MFGDEPT
CHAR(3),MARKUPSMALLINT,SALESDEPTCHAR(3),CURDATEDATENOTNULL)
2)CREATEGLOBALTEMPORARYTABLETEMPPRODLIKEPROD

3)DROPTABLETEMPPROD

***********IMP*********thetemporarytableiscreatedonlywhenwhensomeSQL
operationisdoneonitlike(select,update)
4)onemorewaytocreateatemporarytableistousethecommand
declareglobaltemporary
table
name,forthisatemporaryDBandtemporaryTShavetobecreatedasfollows:
CREATEDATABASEDTTDBASTEMP
CREATETABLESPACEDTTTSINDTTDBSEGSIZE4
Thesecondkindoftemporarytableexistsonlyuntilthesessionexists

HandlingNULLvalues:
UPDATEIBMGRP.MEMBERDETAILSSETLASTNAME='NULL'WHERELASTNAME
ISNULL

VIEWS

Itisalogicalderivationofatablefromothertable/tables.AViewdoesnotexistinitsown

right.

Theyprovideacertainamountiflogicalindependence

Theyallowthesamedatatobeseenbydifferentusersindifferentways

InDB2aviewthatistoacceptaupdatemustbederivedfromasinglebasetable

Aliases

Meananothernameforthetable.

Aliasesareusedbasicallyforaccessingremotetables(indistributeddataprocessing),which
addalocationprefixtotheirnames.

Usingaliasescreatesashortername.

Synonym

Alsomeansanothernameforthetable,butisprivatetotheuserwhocreatedit.

Syntax:
CREATEVIEW<Viewname>(<columns>)
ASSubquery(SubquerySELECTFROMotherTable(s))
CREATEALIAS<Aliasname>FOR<Tablename>
CREATESYNONYM<Synonymname>FOR<Tablename>

CREATEVIEWIBMGRP.VIEW1ASSELECTFIRSTNAME,LASTNAME
FROMIBMGRP.MEMBERDETAILS

UPDATEIBMGRP.VIEW1SETLASTNAME='1NULL'WHERELASTNAME='NULL'
*******WhenaVIEWisupdatedthetableisalsoupdated*******

EmbeddedSQL

ItislikethefileI/O

NormallytheembeddedSQLstatementscontainthehostvariablescodedwiththeINTOclause
oftheSELECTstatement.

TheyaredelimitedwithEXECSQL......ENDEXEC.

E.g.EXECSQL
SELECTEmpno,Empname
INTO:Hempno,:Hempname
FROMEMPLOYEE
WHEREempno=1001
ENDEXEC.
CURSOR:

UsedwhenalargenumberofrowsaretobeSelected

Canbelikenedtoapointer

CanbeusedformodifyingdatausingFORUPDATEOFclause

Thefour(4)Cursorcontrolstatementsare

Declare
:nameassignedforaparticularSQLstatement

Open
:readiesthecursorforrowretrievalsometimesbuildstheresulttable.Howeveritdoes
notassignvaluestothehostvariables

Fetch
:returnsdatafromtheresultstableonerowatatimeandassignsthevaluetospecified
hostvariables

Close
:releasesallresourcesusedbythecursor

DECLARE
:
EXECSQL

DECLAREEMPCURCURSORFOR
SELECTEmpno,Empname,Dept,Job
FROMEMP
WHEREDept='D11'
FORUPDATEOFJob

ENDEXEC.

OPEN:

EXECSQL
OPENEMPCUR
ENDEXEC.

FETCH:

EXECSQL
FETCHEMPCUR
INTO:Empno,:Empname,:Dept,:Job
ENDEXEC.

CLOSE
E.g.FortheClosestatement
EXECSQL
CLOSEEMPCUR
ENDEXEC.

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.FortheUpdatestatementusingcursors

EXECSQL
UPDATEEMP
SetJob=:Newjob
WHEREcurrentofEMPCUR

ENDEXEC.

DELETE
E.g.FortheDeletestatementusingcursors
EXECSQL
DELETEFROMEMP
WHEREcurrentofEMPCUR

ENDEXEC.

Program preparation:

PRECOMPILE
---> separates all the DB2 code and writes it in a DBRM and Modified source
code and DBRM are tagged with

SearchesalltheSQLstatementsandDB2relatedINCLUDEmembersandcommentsoutevery
SQLstatementintheprogram

TheSQLstatementsarereplacedbyaCALLtotheDB2runtimeinterfacemodule,alongwith
parameters.

AllSQLstatementsareextractedandputinaDatabaseRequestModule(DBRM)

PlacesatimestampinthemodifiedsourceandtheDBRMsothatthesearetied.Ifthereis
amismatchinthisaruntimeerrorof818,timestampmismatchoccurs

AllDB2relatedINCLUDEstatementsmustbeplacedbetweenEXECSQL&ENDEXEC
keywordsfortheprecompilertorecognizethem

COMPILEandLINK:
>OnlyCOBOLcodeiscompiled

ModifiedprecompilerCOBOLoutputiscompiled

Compiledsourceislinkeditedtoanexecutableloadmodule

AppropriateDB2hostlanguageinterfacemoduleshouldalsobeincludedinthelinkeditstep(i.e
DSNELI)

CodingSQLinCOBOL:

DeclaringTABLE/VIEWSisCOBOLprogramisnotmandatorybutithelps
documentation.AlsoiftheSQLstatementsdonotmatchwiththetable
declarations,theDBRMwhenbindedwillthoughwarningmessages


OnewaytodeclareatableorviewistocodeaDECLAREstatementinthe
WORKINGSTORAGESECTIONorLINKAGESECTIONwithintheDATA
DIVISIONofyourCOBOLprogram.Specifythenameofthetableandlisteach
columnanditsdatatype.Whenyoudeclareatableorview,youspecify
DECLAREtablenameTABLEregardlessofwhetherthetablenamereferstoa
tableoraview.Forexample,theDECLARETABLEstatementforthe
DSN8810.DEPTtablelookslikethefollowingDECLAREstatementinCOBOL:
EXECSQL
DECLAREDSN8810.DEPT
TABLE(DEPTNOCHAR(3)NOTNULL,
DEPTNAMEVARCHAR(36)NOTNULL,
MGRNOCHAR(6),ADMRDEPTCHAR(3)NOTNULL,
LOCATIONCHAR(16))
ENDEXEC.

UsageofHOSTVARIABLEs:

EXECSQL
SELECTLASTNAME,WORKDEPT
INTO:CBLNAME,:CBLDEPT
FROMDSN8810.EMP
FETCHFIRST1ROWONLY
ENDEXEC.

UsingbothtablecolumnandhostvariableinthesameSQLstatement:
MOVE4476TORAISE.
MOVE000220TOPERSON.
EXECSQL
SELECTEMPNO,LASTNAME,SALARY,:RAISE,
SALARY+:RAISE
INTO:EMPNUM,:PERSONNAME,:EMPSAL,:EMPRAISE,:EMPTTL
FROMDSN8810.EMP
WHEREEMPNO=:PERSONENDEXEC.

Thefollowingresultshavecolumnheadingsthatrepresentthenamesofthehostvariables:
EMPNUMPERSONNAMEEMPSALEMPRAISEEMPTTL
=========================================
000220LUTZ29840447634316

Updating multiple rows:

MOVE D11 TO DEPTID.


EXEC SQL
UPDATE DSN8810.EMP
SET SALARY = 1.10 * SALARY
WHERE WORKDEPT = :DEPTID
END-EXEC.
Inserting Data
:
EXEC SQL
INSERT INTO DSN8810.ACT
VALUES (:HV-ACTNO, :HV-ACTKWD, :HV-ACTDESC)
END-EXEC.
Update a row with null value:
EXEC SQL
UPDATE DSN8810.EMP
SET PHONENO = :NEWPHONE:PHONEIND
WHERE EMPNO = :EMPID
END-EXEC.
Null indicator should be:
-1 if data is null
0 if data is notnull
+ve if data is truncated when passed to the host variable
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.
*************** Usage of cursors *********************
--> 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:
EXEC SQL DELETE FROM DSN8810.EMP WHERE CURRENT OF C1 END-EXEC.
Cursor CLOSE:
EXEC SQL CLOSE C1 END-EXEC.
********* ---> 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.
With rowset positioning a particular row can be updated/deleted, let say
EXEC SQL
UPDATE DSN8810.EMP
SET SALARY = 50000
FOR CURSOR C1 FOR ROW 5 OF ROWSET
END-EXEC.
Preparing embedded SQL statements in COBOL:
1) Mandatory to declare SQL communication area:
A COBOL program that contains SQL statements must include one or both of the following
host variables:
a) An SQLCODE variable declared as PIC S9(9) BINARY, PIC S9(9) COMP-4, PIC S9(9)
COMP-5, or PICTURE S9(9) COMP
b) An SQLSTATE variable declared as PICTURE X(5)
The above declarations can go in WORKING STORAGE SECTION OR DATA
DIVISION

Alternatively, you can include an SQLCA, which contains the SQLCODE and SQLSTATE
variables.
EXEC SQL INCLUDE SQLCA 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.
SELECTEMPNO,LASTNAME,
CASESUBSTR(WORKDEPT,1,1)
WHEN'A'THEN'Administration'
WHEN'B'THEN'HumanResources'
WHEN'C'THEN'Design'
WHEN'D'THEN'Operations'
END
FROMEMPLOYEE
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:
SELECTEMPNO,WORKDEPT,SALARY+COMMFROMEMPLOYEE
WHERE(CASEWHENSALARY=0THEN0
ELSECOMM/(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.
SELECTREF_ID,PAYMT_PAST_DUE_CT,
CASE
WHENPAYMT_PAST_DUE_CT=0THEN0
WHENPAYMT_PAST_DUE_CT>0THEN
SUM(BAL_AMT/PAYMT_PAST_DUE_CT)
END
FROMPAY_TABLE
GROUPBYREF_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
is performed before the division.

SELECTREF_ID,PAYMT_PAST_DUE_CT,
SUM(CASE
WHENPAYMT_PAST_DUE_CT=0THEN0
WHENPAYMT_PAST_DUE_CT>0THEN
BAL_AMT/PAYMT_PAST_DUE_CT
END)
FROMPAY_TABLE
GROUPBYREF_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.
SELECTCASE_DEPT,MAX(SALARY),MIN(SALARY),AVG(SALARY)
FROM(SELECTSALARY,CASEWHENWORKDEPT='A00'ORWORKDEPT='E21'
THEN'A00_E21'
WHENWORKDEPT='D11'ORWORKDEPT='E11'
THEN'D11_E11'
ELSEWORKDEPT
ENDASCASE_DEPT
FROMDSN8910.EMP)X
GROUPBYCASE_DEPT

DB2 PLAN/PACKAGE:
each package corresponds to a single DBRM
All packages can be grouped together to form a PLAN.
Advantage of grouping all PACKAGES instead of using them as directly DBRM's is that, IF a
collection of DBRM's is made as a plan then any change in one DBRM results in rebinding of
the whole PLAN
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.
Conceptual background:
Concurrency must be controlled to prevent lost updates and
such possibly undesirable effects as unrepeatable reads and access to uncommitted data.
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, As 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 As value is not later committed, but backed out, Bs 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.
Different isolation levels
Cursor stability: once the commit or rollback happens any other application can access
Repeatable read: If RR is placed exclusive locks are put on the table, no other transaction
can access that particular row until tarnsaction that held the record with RR is completed
CS--> More performance
RR--> more integrity
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
*********IMP****** ACQUIRE(ALLOCATE) and RELEASE(COMMIT) options are not
allowed
*******IMP***********if RELEASE(COMMIT) is used , but cursor is declared with HOLD
option the LOCK is still maintained post the commit position
CURRENTDATA(YES/NO):
To guarantee data stability when a read only cursor is
accessing data with CS isolation level
READ ONLY is specified when cursor is delcared
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
Q11) What is a buffer pool?
A11) A buffer pool is main storage that is reserved to satisfy the buffering requirements for
one or more
tablespaces or indexes, and is made up of either 4K or 32K pages.
Q12) How many buffer pools are there in DB2?
A12) There are four buffer pools: BP0, BP1, BP2, and BP32.
DB2 DBA:
CREATE TABLESPACE TB IN DATABASENAME using storagegroup stgname priqty secqty
erase no --> do not erase tables when table space is dropped
locksize any
bufferpool bp0
close no <== close the table spave when not accessed
freepage 5 (Percentage of space that has to be left before any other table space starts)
pctfree 10 (percentage of each page that has to be left free)
SEGSIZE 32 (--segmented table space) more than one table (4 to 64) in multiples of four
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
Q21) What are data types?
A21) They are attributes of columns, literals, and host variables. The data types are
SMALLINT,
INTEGER, FLOAT, DECIMAL, CHAR, VARCHAR, DATE and TIME.
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
Q44) What information is held in SYSIBM.SYSCOPY?
A44) The SYSIBM.SYSCOPY table contains information about image copies made of the
tablespaces.
Q45) What information is contained in a SYSCOPY entry?
A45) Included is the name of the database, the table space name, and the image copy
type(full or
incremental etc.,) as well as the date and time each copy was made.
Q46) What information can you find in SYSIBM.SYSLINKS table?
A46) The SYSIBM.SYSLINKS table contains information about the links between tables
created by
referential constraints.
Q47) Where would you find information about the type of database authority held by the
user?
A47) SYSIBM.SYSDBAUTH.
SYSIBM.SYSINDEXES
SYSIBM.SYSVIEWS
Q148) What is Skeleton cursor table (SKCT)?
A148) The Executable form of a Plan. This is stored in sysibm.sct02 table
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)
Utility to run a plan
Use IKJEFT01 utility program to run the above DSN command in a JCL.
Q65) How can you quickly find out the number of rows updated after an update statement?
A65) Check the value stored in
SQLERRD(3).
Q108) What is CHECK PENDING ?
A108) When a table is LOADed with ENFORCE NO option, then the table is left in CHECK
PENDING
status. It means that the LOAD utility did not perform constraint checking.
Q109) What is QUIESCE?
A109) A QUIESCE flushes all DB2 buffers on to the disk. This gives a correct snapshot of the
database
and should be used before and after any IMAGECOPY to maintain consistency.
Q113) What is sqlcode -922 ?
A113) Authorization failure
Q114) What is sqlcode -811?
A114) SELECT statement has resulted in retrieval of more than one row.
Q145) What is the error code -803 ?
A145) unique index violation
Q167) What is the meaning of -805 SQL return code?
A167) Program name not in plan. Bind the plan and include the DBRM for the program
named as part of
the plan
Q115) What does the sqlcode of -818 pertain to? - GS
A115) This is generated when the consistency tokens in the DBRM and the load module are
different.
Q122) What is filter factor?
A122) One divided by the number of distinct values of a column.
Q123) What is index cardinality? - GS
A123) The number of distinct values a column or columns contain
Q150) Can we declare DB2 HOST variable in COBOL COPY book?
A150) NO. If we declare DB2 host variable in COBOL COPY book, at the time of
Pre-compilation we
get the host variable not defined, because pre-compiler will not expand COBOL COPY book.
So
we declare it either in DCLGEN with EXEC SQL INCLUDE DCLGEN name END-EXEC or we
directly hardcode it in the working storage section.

PLAN CREATION:
BIND PLAN(????????) - **********>>> ENTER PLAN NAME
PKLIST(SEALAND.????????, - **********>>> ENTER MEMBER NAME
SEALAND.????????, - **********>>> (MULTIPLE MEMBERS
SEALAND.????????) - **********>>> FOR EACH PLAN)
QUALIFIER(TEST) - **********>>> MUST ALWAYS BE TEST
OWNER(????) - **********>>> ENTER YOUR TSO ID
ACTION(REPLACE) RETAIN VALIDATE(BIND) ISOLATION(CS) FLAG(I) ACQUIRE(USE) RELEASE(COMMIT) EXPLAIN(YES)
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.
Follow the example:
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:
1) MEMBER(MEMNAME): MEMBER is the member name in which the DBRM is stored

2) LIB('DBRMLIB'): PDS in which DBRM is present

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

7) EXPLAIN(YES|NO) : PLAN_TABLE is updated with the access path by the optimizer

SQL CODES:

SQLCODE
The SQLCODE field contains the SQL return code. The code can be zero (0), negative or
positive.
0meanssuccessfulexecution.

Negativemeansunsuccessfulwithanerror.

Anexampleis911whichmeansatimeouthasoccurredwitha
rollback
.

Positivemeanssuccessfulexecutionwithawarning.
Anexampleis+100whichmeansnorowsfound.
Here is a more comprehensive list of the SQLCODEs for DB2:

[
edit
] Zero (Successful)
0Successful

[
edit
] Negative values (Errors)
102Stringconstantistoolong.
117ThenumberofvaluesintheINSERTdoesnotmatchthenumberofcolumns.
180BaddatainDate/Time/Timestamp.
181BaddatainDate/Time/Timestamp.
199Illegaluseofthespecifiedkeyword.

204ObjectnotdefinedtoDB2.
205Columnnamenotintable.
206ColumndoesnotexistinanytableoftheSELECT.
216Notthesamenumberofexpressionsonbothsidesofthecomparisonina
SELECT.
224FETCHcannotmakeanINSENSITIVEcursorSENSITIVE.
229ThelocalespecifiedinaSETLOCALEstatementwasnotfound.

305Nullindicatorneeded.
311Varchar,insertorupdate.LENfieldwiththerightdatalengthnotset.

482Theprocedurereturnednolocators.

501CursornotopenonFETCH.
502Openingcursorthatisalreadyopen.
503Updatingcolumnneedstobespecified.
530ReferentialintegritypreventingtheINSERT/UPDATE
532Referentialintegrity(DELETERESTRICTrule)preventingtheDELETE.
536Referentialintegrity(DELETERESTRICTrule)preventingtheDELETE.
545CheckconstraintpreventingtheINSERT/UPDATE.
551Authorizationfailure

747Thetableisnotavailable.

803Duplicatekeyoninsertorupdate.
805DBRMorpackagenotfoundinplan.
811MorethanonerowretrievedinSELECTINTO.
818Planandprogram:timestampmismatch.

904Unavailableresource.Someoneelseislockingyourdata.
911Deadlockortimeout.Rollbackhasbeendone.
913Deadlockortimeout.Norollback.
922Authorizationneeded.
927Thelanguageinterfacewascalledbutnoconnectionhadbeenmade.
936
1741

20000
302DatathatisfetchedfromDB2ismorethanthehostvariable

[
edit
] Positive Values (Warnings)
+100Rownotfoundorendofcursor.
+222TryingtofetcharowwithinaDELETEstatement.
+223TryingtofetcharowwithinanUPDATEstatement.
+231FETCHafteraBEFOREorAFTERbutnotonavalidrow.
+304Valuecannotbeassignedtothishostvariablebecauseitisoutofrange.
+802Thenullindicatorwassetto2asanarithmeticstatementdidn'twork.

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
SEGMENTED table space:
Each page is of size 4 kb to 64 KB
A page is divided into segments
Each segment can relate to only one table.
So if a page lock is applied only relevant segments to the particular table are locked.
If rows are retrieved only relevant segments are accessed
CREATETABLESPACEMYTS
INMYDB
USINGSTOGROUPMYSTOGRP
PRIQTY30720
SECQTY10240
SEGSIZE32
LOCKSIZETABLE
BUFFERPOOLBP0
CLOSENO

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
Segmented table space: One table per page.
ALTER TABLE:
ALTER TABLE IBMGRP.ALTER ALTER COLUMN NAME SET DATA TYPE VARCHAR(100);
VIEW:--> WITH CHECK OPTION WILL THROW ERRORS IF ANY
CREATE VIEW PRIORITY_ORDERS

AS SELECT * FROM ORDERS WHERE RESPONSE_TIME < 4


WITH CHECK OPTION
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 views 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.
Trigger
:<-- Every time an insert happens the emp no is incremented by 1
CREATE TRIGGER NAME_INC
AFTER INSERT ON IBMGRP.ALTER
FOR EACH ROW MODE DB2SQL
UPDATE NAMID SET NAMID = NAMID + 1;
Delete
<-- Always use it with where to avoid mass delete of rows
DELETE FROM SALES
WHERE COMPANY = XYZ
The SELECT statement
:
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
Where
can be used with :
Relational Predicates (Comparisons)
BETWEEN
LIKE
IN
EXISTS
NULL
Relational predicates

< (Less than)


> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
= (Equal to)
<> (Not equal to)
NOT (Negation)

BETWEEN:
SELECT EMPNO, SALARY FROM EMPLOYEES
WHERE SALARY BETWEEN 10000.00 AND 20000.00
>= 10K and <= 20000
The LIKE predicate:
The underscore character (_) is treated as a wild card character that stands for any single
alphanumeric character.
The percent character (%) is treated as a wild card character that stands for any sequence
of alphanumeric characters.
SELECT EMPNO, LASTNAME FROM EMPLOYEES
WHERE LASTNAME LIKE S%
IN predicate:
SELECT LASTNAME, WORKDEPT FROM EMPLOYEES
WHERE WORKDEPT IN (SELECT DEPTNO FROM DEPARTMENTS
WHERE DEPTNAME = OPERATIONS OR
DEPTNO = SOFTWARE SUPPORT)
*** The EXISTS CLAUSE *****
The EXISTS predicate is used to determine whether or not a particular value exists in a
given table.
The EXISTS predicate is always followed by a subquery
, and it returns either TRUE or
FALSE to
indicate whether a specific value is found in the result data set produced by the subquery.
Thus, if
you wanted to find out which values found in the column named DEPTNO in a table named
DEPARTMENT are used in the column named WORKDEPT found in a table named
EMPLOYEES, you could do so by executing a SELECT statement that looks something like
this:
SELECT DEPTNO, DEPTNAME FROM DEPARTMENT
WHERE EXISTS
(SELECT WORKDEPT FROM EMPLOYEES
WHERE WORKDEPT = DEPTNO)
AGGREGATE FUNCTION:
When MAX,MIN,SUM,AVG,COUNT(*) are used, the rows having null values are discarded.
FOr example:
MyTable

ID
1
2
3
4
5

Name
John
Jack
Jim
Joe
Josh

Amount
37
NULL
5
12
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
Inner join Vs Outer Join
Inner join only returns matching rows
Outer join returns matching rows and non matching rows(Depending on Left,Right,Full)
SELECT LASTNAME, DEPTNAME
FROM EMPLOYEES E LEFT OUTER JOIN DEPARTMENT D
ON
E.WORKDEPT = D.DEPTNO
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:
Intent Share/ Intent Upddate.
The above two locks are only the ones which can get a lock at row level or page level
Share/Update/eXclusive locks:- These locks are obtained at table 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
EXEC SQL LOCK TABLE TAB1 IN SHARE MODE END-EXEC

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)
DECLARE CURSOR C1 FOR SELECT
WITH RR/RS/CS/UR
The above will override bind isolation levels

Example for DB2 SQLCODE: -922


READY
DSN SYSTEM(DB2R)
DSN
BIND PLAN(FCURF2) PKLIST(DB2RLOC.IBMGRP.*) ACT(REP) ISOLATION(CS)
DSNT210I -DB2R BIND AUTHORIZATION ERROR
USING R06388 AUTHORITY
PLAN = FCURF2
PRIVILEGE = BINDADD
DSNT201I -DB2R BIND FOR PLAN FCURF2 NOT SUCCESSFUL
DSN
EXPLAIN (NO)
OWNER(IBMGRP)
DSNE118E EXPLAIN NOT VALID COMMAND
DSN
END
Authorization(BINDADD) not present to add a DBRM to a PACKAGE
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

Das könnte Ihnen auch gefallen