+ All Categories
Home > Documents > DB2 Basics

DB2 Basics

Date post: 05-Nov-2015
Category:
Upload: pkonduri
View: 37 times
Download: 1 times
Share this document with a friend
Description:
Mainframe DB2 Basics
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' Data Definition Language (DDL) Create, Alter and Drop Data Manipulation Language (DML) Select, Insert, Update and Delete Data Control Language (DCL) Grant and Revoke All the tables are created in table spaces. Table spaces reside on ESDS or LDS Creation of temporary tables: 1) CREATE GLOBAL TEMPORARY TABLE TEMPPROD (SERIAL CHAR(8) NOT NULL, DESCRIPTION VARCHAR(60) NOT NULL, MFGCOST DECIMAL(8,2), MFGDEPT CHAR(3), MARKUP SMALLINT, SALESDEPT CHAR(3), CURDATE DATE NOT NULL); 2) CREATE GLOBAL TEMPORARY TABLE TEMPPROD LIKE PROD; 3) DROP TABLE TEMPPROD; *********** 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 Handling NULL values: UPDATE IBMGRP.MEMBERDETAILS SET LASTNAME = 'NULL' WHERE LASTNAME IS NULL; VIEWS It is a logical derivation of a table from other table/tables. A View does not exist in its own
Transcript
  • 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,AlterandDropDataManipulationLanguage(DML)Select,Insert,UpdateandDeleteDataControlLanguage(DCL)GrantandRevokeAllthetablesarecreatedintablespaces.TablespacesresideonESDSorLDSCreationoftemporarytables:1)CREATEGLOBALTEMPORARYTABLETEMPPROD(SERIALCHAR(8)NOTNULL,DESCRIPTIONVARCHAR(60)NOTNULL,MFGCOSTDECIMAL(8,2),MFGDEPTCHAR(3),MARKUPSMALLINT,SALESDEPTCHAR(3),CURDATEDATENOTNULL)2)CREATEGLOBALTEMPORARYTABLETEMPPRODLIKEPROD3)DROPTABLETEMPPROD***********IMP*********thetemporarytableiscreatedonlywhenwhensomeSQLoperationisdoneonitlike(select,update)4)onemorewaytocreateatemporarytableistousethecommanddeclareglobaltemporarytablename,forthisatemporaryDBandtemporaryTShavetobecreatedasfollows:CREATEDATABASEDTTDBASTEMPCREATETABLESPACEDTTTSINDTTDBSEGSIZE4ThesecondkindoftemporarytableexistsonlyuntilthesessionexistsHandlingNULLvalues:UPDATEIBMGRP.MEMBERDETAILSSETLASTNAME='NULL'WHERELASTNAMEISNULLVIEWSItisalogicalderivationofatablefromothertable/tables.AViewdoesnotexistinitsown

  • right.TheyprovideacertainamountiflogicalindependenceTheyallowthesamedatatobeseenbydifferentusersindifferentwaysInDB2aviewthatistoacceptaupdatemustbederivedfromasinglebasetableAliasesMeananothernameforthetable.Aliasesareusedbasicallyforaccessingremotetables(indistributeddataprocessing),whichaddalocationprefixtotheirnames.Usingaliasescreatesashortername.SynonymAlsomeansanothernameforthetable,butisprivatetotheuserwhocreatedit.Syntax:CREATEVIEW()ASSubquery(SubquerySELECTFROMotherTable(s))CREATEALIASFORCREATESYNONYMFORCREATEVIEWIBMGRP.VIEW1ASSELECTFIRSTNAME,LASTNAMEFROMIBMGRP.MEMBERDETAILSUPDATEIBMGRP.VIEW1SETLASTNAME='1NULL'WHERELASTNAME='NULL'*******WhenaVIEWisupdatedthetableisalsoupdated*******EmbeddedSQLItislikethefileI/ONormallytheembeddedSQLstatementscontainthehostvariablescodedwiththeINTOclauseoftheSELECTstatement.TheyaredelimitedwithEXECSQL......ENDEXEC.E.g.EXECSQLSELECTEmpno,Empname INTO:Hempno,:HempnameFROMEMPLOYEEWHEREempno=1001ENDEXEC.CURSOR: UsedwhenalargenumberofrowsaretobeSelectedCanbelikenedtoapointerCanbeusedformodifyingdatausingFORUPDATEOFclause

  • Thefour(4)CursorcontrolstatementsareDeclare:nameassignedforaparticularSQLstatementOpen:readiesthecursorforrowretrievalsometimesbuildstheresulttable.HoweveritdoesnotassignvaluestothehostvariablesFetch:returnsdatafromtheresultstableonerowatatimeandassignsthevaluetospecifiedhostvariablesClose:releasesallresourcesusedbythecursorDECLARE:EXECSQLDECLAREEMPCURCURSORFORSELECTEmpno,Empname,Dept,JobFROMEMPWHEREDept='D11' FORUPDATEOFJobENDEXEC.OPEN: EXECSQLOPENEMPCURENDEXEC.FETCH: EXECSQLFETCHEMPCURINTO:Empno,:Empname,:Dept,:JobENDEXEC.CLOSEE.g.FortheClosestatementEXECSQLCLOSEEMPCURENDEXEC.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. UPDATEE.g.FortheUpdatestatementusingcursors

  • EXECSQLUPDATEEMPSetJob=:Newjob WHEREcurrentofEMPCURENDEXEC.DELETEE.g.FortheDeletestatementusingcursorsEXECSQLDELETEFROMEMP WHEREcurrentofEMPCURENDEXEC.Program preparation: PRECOMPILE ---> separates all the DB2 code and writes it in a DBRM and Modified source code and DBRM are tagged with SearchesalltheSQLstatementsandDB2relatedINCLUDEmembersandcommentsouteverySQLstatementintheprogramTheSQLstatementsarereplacedbyaCALLtotheDB2runtimeinterfacemodule,alongwithparameters.AllSQLstatementsareextractedandputinaDatabaseRequestModule(DBRM)PlacesatimestampinthemodifiedsourceandtheDBRMsothatthesearetied.Ifthereisamismatchinthisaruntimeerrorof818,timestampmismatchoccursAllDB2relatedINCLUDEstatementsmustbeplacedbetweenEXECSQL&ENDEXECkeywordsfortheprecompilertorecognizethemCOMPILEandLINK:>OnlyCOBOLcodeiscompiledModifiedprecompilerCOBOLoutputiscompiledCompiledsourceislinkeditedtoanexecutableloadmoduleAppropriateDB2hostlanguageinterfacemoduleshouldalsobeincludedinthelinkeditstep(i.eDSNELI)CodingSQLinCOBOL:DeclaringTABLE/VIEWSisCOBOLprogramisnotmandatorybutithelpsdocumentation.AlsoiftheSQLstatementsdonotmatchwiththetabledeclarations,theDBRMwhenbindedwillthoughwarningmessages

  • OnewaytodeclareatableorviewistocodeaDECLAREstatementintheWORKINGSTORAGESECTIONorLINKAGESECTIONwithintheDATADIVISIONofyourCOBOLprogram.Specifythenameofthetableandlisteachcolumnanditsdatatype.Whenyoudeclareatableorview,youspecifyDECLAREtablenameTABLEregardlessofwhetherthetablenamereferstoatableoraview.Forexample,theDECLARETABLEstatementfortheDSN8810.DEPTtablelookslikethefollowingDECLAREstatementinCOBOL:EXECSQLDECLAREDSN8810.DEPTTABLE(DEPTNOCHAR(3)NOTNULL,DEPTNAMEVARCHAR(36)NOTNULL,MGRNOCHAR(6),ADMRDEPTCHAR(3)NOTNULL,LOCATIONCHAR(16))ENDEXEC.UsageofHOSTVARIABLEs:EXECSQLSELECTLASTNAME,WORKDEPTINTO:CBLNAME,:CBLDEPTFROMDSN8810.EMPFETCHFIRST1ROWONLYENDEXEC.UsingbothtablecolumnandhostvariableinthesameSQLstatement:MOVE4476TORAISE.MOVE000220TOPERSON.EXECSQLSELECTEMPNO,LASTNAME,SALARY,:RAISE,SALARY+:RAISEINTO:EMPNUM,:PERSONNAME,:EMPSAL,:EMPRAISE,:EMPTTLFROMDSN8810.EMPWHEREEMPNO=:PERSONENDEXEC.Thefollowingresultshavecolumnheadingsthatrepresentthenamesofthehostvariables:EMPNUMPERSONNAMEEMPSALEMPRAISEEMPTTL=========================================000220LUTZ29840447634316Updating 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'ENDFROMEMPLOYEEExample 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+COMMFROMEMPLOYEEWHERE(CASEWHENSALARY=0THEN0ELSECOMM/(SALARY+COMM)END)>0.25Example 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,CASEWHENPAYMT_PAST_DUE_CT=0THEN0WHENPAYMT_PAST_DUE_CT>0THENSUM(BAL_AMT/PAYMT_PAST_DUE_CT)ENDFROMPAY_TABLEGROUPBYREF_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(CASEWHENPAYMT_PAST_DUE_CT=0THEN0WHENPAYMT_PAST_DUE_CT>0THENBAL_AMT/PAYMT_PAST_DUE_CTEND)FROMPAY_TABLEGROUPBYREF_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'ELSEWORKDEPTENDASCASE_DEPTFROMDSN8910.EMP)XGROUPBYCASE_DEPTDB2 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
  • 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.

  • Anexampleis911whichmeansatimeouthasoccurredwitharollback.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.216NotthesamenumberofexpressionsonbothsidesofthecomparisoninaSELECT.224FETCHcannotmakeanINSENSITIVEcursorSENSITIVE.229ThelocalespecifiedinaSETLOCALEstatementwasnotfound.305Nullindicatorneeded.311Varchar,insertorupdate.LENfieldwiththerightdatalengthnotset.482Theprocedurereturnednolocators.501CursornotopenonFETCH.502Openingcursorthatisalreadyopen.503Updatingcolumnneedstobespecified.530ReferentialintegritypreventingtheINSERT/UPDATE532Referentialintegrity(DELETERESTRICTrule)preventingtheDELETE.536Referentialintegrity(DELETERESTRICTrule)preventingtheDELETE.545CheckconstraintpreventingtheINSERT/UPDATE.551Authorizationfailure747Thetableisnotavailable.803Duplicatekeyoninsertorupdate.805DBRMorpackagenotfoundinplan.811MorethanonerowretrievedinSELECTINTO.818Planandprogram:timestampmismatch.904Unavailableresource.Someoneelseislockingyourdata.911Deadlockortimeout.Rollbackhasbeendone.913Deadlockortimeout.Norollback.922Authorizationneeded.927Thelanguageinterfacewascalledbutnoconnectionhadbeenmade.9361741

  • 20000302DatathatisfetchedfromDB2ismorethanthehostvariable

    [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 CREATETABLESPACEMYTSINMYDBUSINGSTOGROUPMYSTOGRPPRIQTY30720SECQTY10240SEGSIZE32LOCKSIZETABLEBUFFERPOOLBP0CLOSENOBufferpool: 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:
  • < (Less than) > (Greater than) = (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
  • ID Name Amount 1 John 37 2 Jack NULL3 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 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


Recommended