Sie sind auf Seite 1von 63

COPY PENDING A state in which, an Image Copy on a table needs to be taken, In this status, the table is available only

for queries. You cannot update this table. To remove the COPY PENDING status, you take an image copy or use REPAIR utility. CHECK PENDING 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. how can i remove CHECK PENDING for the child tables(if any constraint checking is made) with in the upload jcl. You can try with the SYSIN option in the upload JCL : REPAIR SET TABLESPACE SWCOSTII.SWCOSTSB NOCHECKPEND have one Main program (non db2) calling 2 subprograms :> subprogram1 is cobol program > subprogram2 is cobol/db2 program. > I have the following questions :> > 1. If I change only subprogram2 , which all components i should > compile/link/bind so that i can test subprogram2. > 2. If I change only subprogram1, which all components I should > compile/link/bind so that i can test subprogram1. > 3. If i change only the main program, which all components I should > compile/link/bind so that i can test the main program. > 4. If i change all the components what is the compile/link/bind process. Compilation of the programs depend upon the type of call made for the 2 subprograms. (static / dynamic) 1) Dynamic call: Compile and bind the subprog 2 only Static call: compile & bind subprog 2 & main prog 2) Dynamic call: Compile / link only sub prog 1 Static Call: compile & link subprog 1 & main prog and compile / link / bind sub prog 2 also 3) For the main prog changes...you will have to compile / link sub prog 1 and compile / link / bind subprog 2 4) If you are making changes in all the programs...you will need to compile / link / bind all the 3 programs. compile / link sub prog 1

compile / link / bind sub prog 2 with the main prog would anyone please give me the query for the below requirements 1.Need to change all the nullable values for column department with value 'abc' for a table.Here the column department is nullable. 2.I have a table with three columns a1,a2,a3.Here a1 is the primary key.The requirement is such that I have to add one more column a4 to this table and make this column a4 as the primary key instead of a1.How should I proceed with this requirement.Please give me the steps. All sorts of help appreciated. 1) UPDATE DEPTTBL SET DEPARTMENT = 'ABC' WHERE DEPARTMENT IS NULL 2) follow the procedure below: Code: a) drop the primary key constraint b) add a column c) based on conditions, make each row value unique and then add the primary key constraint. This is possible only when the data added to the column is distinct. But you may need to create an UNIQUE Index on column A4 before adding the Primary key. (if you are not using a Schema Processor). DSNDB01 DB2 Directory tablespace DSNDB06 DB2 catalog tablespace I need a small clarification while giving the following instruction under the SYSTSIN DD for running the cobol-db2 program.After invoking the ikjef utility under the SYSTSIN dd we will be giving the following commands DSN SYSTEM(xxxx) RUN PROGRAM(xxx70BD) PLAN(xxx470BD) LIB('xxxS01T.OBJ.LOADLIB') /* here what the 'DSN SYSTEM(xxxx)' instruction referring?Why we need to give this. You know COBOL + DB2 programs are executed using IKJEFT* programs. DB2 has its own subsystem like TEST, PRODUCTION, QA etc. Here, DSN SYSTEM ('DB2T') IKJEFT* is TSO TMP program, which identifies the sub system in which the

program needs to be invoked, Then it finds out the program and its associated plan & loadlib. need to find out the primary key of an existing table. (That's not my own) Execute the following query, you will get the primary key for the table SYSIBM.SYSCOLUMNS identifies columns of a parent key in column KEYSEQ; a nonzero value indicates the place of a column in the parent key. Code: SELECT TBCREATOR, TBNAME, NAME, KEYSEQ FROM SYSIBM.SYSCOLUMNS WHERE TBCREATOR = 'creater id' AND TBNAME = 'table-name' AND KEYSEQ > 0 ORDER BY KEYSEQ; SYSIBM.SYSINDEXES identifies the primary index of a table by the value P in column UNIQUERULE. Code: SELECT TBCREATOR, TBNAME, NAME, CREATOR, DBNAME, INDEXSPACE FROM SYSIBM.SYSINDEXES WHERE TBCREATOR = 'creator id' AND TBNAME = 'table-name' AND UNIQUERULE = 'P'; have no Authorities to select from SYSIBM tables in our site. How can I find out the primary key While selecting all columns of a table, It displayed in ASCNDING order of the primary key by default. (If you have any other parallel row in asc order, just try by inserting two more rows in des order for all columns) how to find out the foreign key of a table from SYSIBM. Below is the answer of your query.. Code: SELECT TBNAME, COLNAME, COLNO, CREATOR FROM SYSIBM.SYSFOREIGNKEYS WHERE TBNAME = 'table-name'; SYSFOREIGNKEYS table contains one row for every column of every foreign key. To find the relative table of that foreign key, please use SYSIBM.SYSRELS Is there any tool for Cobol-DB2. For writing COBOL-DB2 programs you can use DCLGEN/DB2I to create declaration for tables, Host variables & Indicator Variables.

Can we use the scalar function say MAX in the where clause of a SELECT query to see a user with maximum values ?(or) we have to go for subquery with the inner query selecting the max value i.e select user from table where value in ( select max(value) from table where user='xxx') Just have a doubt on the first part of the question U can use scalar function MAX in Where clause. select EMP-NAME from EMP-table where SALARY= ( select max(SALARY) from EMP-table where DEPT-CD='xxx') ; Similarly you can use this subquery to retrieve the nth max or min value for the column also. Select A.sal from emp A where 2 = (select count (distinct B.sal) from emp B where B.sal >= A.sal) Here, 2nd max salary will be retrieved. Similar results will be obtained from following query select max(salary) from employee where salary < (select max(salary) from employee) 1 . Is there any command to view the structure of a table. eg desc tablename in oracle. 2. Is it possible to alter the size of a column after the table has been created. eg . a field name varchar(20) , i want to alter the size to varchar(25) 3. 1) 2) 3) What is the purpose of using indexing on using a primary key. use DCLGEN No, create a new column, fill in the values Record retrieval is fast and efficient.

how can I run my DB2 program in mainframe? Steps to run the COBOL-DB2 program in mainframes: 1) Code the DB2 program 2) Compile the program (using a JCL with DB2 precompile step)

3) Bind the DBRM to the Plan 4) Use this plan to execute the program using IKJEFT* programs. Your run jcl will contain folloowing in SYSTSIN DSN RUN SYSTEM(your db2 sub-system) PROGRAM(program-name) PLAN(plan-name) LIB(your library) PARM(any parms) What is the exact difference between Table and View? Table is a physical collection of your records. View is just a select statement that uses the records in on or more physical table. It's an logical entity. The main application of view is, it's exactly same as a table (with some restriction), but you can have records of more than one table in a single view. The main usage of view is, you can hide some sensitive columns from your table to an end user, by allowing him to use only the view instead of your table. Is a physical entity containing data.It occupies a part of storage. Views : A virtual table consisting of an SQL select statement that accesses data from one or more tables. A view never stores data. Its used when data acceses needs to be restricted/regulated within groups. Also, a join between different tables can be accessed using a view A view is a specific defined subset of the table in question. we use a view for one of two reasons: 1) Ease of use. You can represent a complex statement in simpler terms in case you want to make that information available in an easier fashion. A good example is that a DBA can write a join of the catalog tables as a view for the application programmers to be able to provide their relevant information fast without much knowledge of what the catalog tables are. 2) Selective security. You might want to limit full access to a table, yet allow access to certain parts of it. A very good example here is an employee table. The employee table would definitely not be a good candidate for granting general access to update, or even select because it would have confidential information that we would not want just anyone to update or even see. But at the same time,

we would want to have the general public be able to see the relevant parts of the employee table for things like employee listings and office phone directories. Therefore, you would create a view containing that relevant information the public should see and then allow access to the view, while limiting access to the whole table. What is the difference between copy and include? The compiler uses copy; DB2 uses include; some of the lib mgmt packages use ++include. COPY statement includes some pre defined cobol statements where u coded copy.this will be understood by the compiler. where as, INCLUDE brings the members of dclgen.though it is similar to copy(in action) precompiler cant recognize copy.so AFAIK copy cant be substituted by include and viceversa. The INLCUDE is an SQL statement that is satisfied in the DB2 pre-compile step where as the COPY statement is satisfied in the COBOL compile step. how can I perform ROW Lock and table Lock in DB2? You can use the LOCKSIZE parameter. Look at the link below to get the more details DB2 Universal Database for OS/390 and z/OS Administration Guide explain about inner join and outer join?Union and UnionALL? with correct definations Inner join: To request an inner join, execute a SELECT statement in which you specify the tables that you want to join in the FROM clause, and specify a WHERE clause or an ON clause to indicate the join condition. Full Outer join: The clause FULL OUTER JOIN includes unmatched rows from both tables. Missing values in a row of the result table contain nulls. Left outer join: The clause LEFT OUTER JOIN includes rows from the table that is specified before LEFT OUTER JOIN that have no matching values in the table that is specified after LEFT OUTER JOIN. Right Outer join: The clause RIGHT OUTER JOIN includes rows from the table that is specified

after RIGHT OUTER JOIN that have no matching values in the table that is specified before RIGHT OUTER JOIN. Example: Code: A join-condition specifies pairings of T1 and T2, where T1 and T2 are the left and right operand tables of its associated JOIN operator. For all possible combinations of rows T1 and T2, a row of T1 is paired with a row of T2 if the join-condition is true. When a row of T1 is joined with a row of T2, a row in the result consists of the values of that row of T1 concatenated with the values of that row of T2. The execution might involve the generation of a null row. The null row of a table consists of a null value for each column of the table, regardless of whether the columns allow null values. The following summarizes the results of the join operations: 1) The result of T1 INNER JOIN T2 consists of their paired rows. 2) The result of T1 LEFT OUTER JOIN T2 consists of their paired rows and, for each unpaired row of T1, the concatenation of that row with the null row of T2. All columns derived from T2 allow null values. 3) The result of T1 RIGHT OUTER JOIN T2 consists of their paired rows and, for each unpaired row of T2, the concatenation of that row with the null row of T1. All columns derived from T1 allow null values. 4) The result of T1 FULL OUTER JOIN T2 consists of their paired rows and, for each unpaired row of T1, the concatenation of that row with the null row of T2, and for each unpaired row of T2, the concatenation of that row with the null row in T1. All columns of the result table allow null values. A join operation is part of a FROM clause; therefore, for the purpose of predicting which rows will be returned from a SELECT statement containing a join operation, assume that the join operation is performed before the other clauses in the statement.

Union: Using the UNION keyword, you can combine two or more SELECT statements to form a single result table. When DB2 encounters the UNION keyword, it processes each SELECT statement to form an interim result table, and then combines the interim result table of each statement. If you use UNION to combine two columns with the same name, the result table inherits that name.

You can use UNION to eliminate duplicates when merging lists of values obtained from several tables.

Union All: If you want to keep duplicates in the result of a UNION, specify the optional keyword ALL after the UNION keyword. Can we upadte view? UPDATE any table thru it's VIEW only if, Code: 1. View has selected from only one base table 2. The view contains all the non-default column of base table Yes Views can be updated if and only if 1) It is from a single table 2) It should be a row-coloum subset of the underlying base table. If coloum in view has scalar or Aggregate functions, view from a single table also cann't be updated. Note: Views cannot have order by or group by clause. How to identify my primary key of the table, if I don't have permission to view SYSIBM.* Tables Try to display all the columns of your table. The primary key column doesn't have any duplicates. If you have any other columns as unique, try to insert a duplicate value for each columns one by one. Using this tech. you can easily identify the primary key. You can try running this SQL SELECT * FROM SYSIBM.SYSKEYS WHERE IXCREATOR='<creator name>' This will give the column which is part of primary key along with the column number, colun sequence and ordering.

difference between IDMS and DB2? Idms is a Network database management system and DB2 is a RDBMS which is Table like structure.NDMS set of records which is having owner and member relationship within the set. What's the Diff betwee Sql Code + and + Means Warning... - Means Error... How can I delete Duplicate records from a Database Table. I don't need those records to be transferred to a new table... I put it clear.. USING only 1 TABLE. Here i have a query which displays the Duplicate records in a table. You can remove the duplicates by replacing SELECT * by DELETE. The table is Shipment_orders and the primary keys are Shipment,purchase_order and item_sku. Quote: /* 1. Query heading */ SELECT * /* Remember to never use SELECT * and write out the field names */ FROM /* 2. Table with duplicates */ SHIPMENT_ORDERS WHERE EXISTS ( SELECT NULL FROM /* 3. Table with duplicates, with an alias */ SHIPMENT_ORDERS b WHERE /* 4. Join each field with *itself*. These are fields that could be Primary Keys */ b.[shipment] = SHIPMENT_ORDERS.[shipment] AND b.[purchase_order] = SHIPMENT_ORDERS.[purchase_order] AND b.[item_sku] = SHIPMENT_ORDERS.[item_sku] GROUP BY /* 5. I must GROUP BY these fields because of the HAVING clause and because these are the possible PK */ b.[shipment], b.[purchase_order], b.[item_sku] HAVING /* 6. This is the determining factor. We can control our output from here. In this case, we want to pick records where the ID is less than the MAX ID */ SHIPMENT_ORDERS.[id] < MAX(b.[id]) ) Here we compare each field to its copy.The GROUP BY clause is used to ensure

that the data is unique. To remove all the duplicated from the table replace the SELECT * with DELETE FROM. 1. Can one declare cursor in procedure division :?: 2. If one can declare a cursor in procedure division then does it differ from one which is declared in working storage :?: ...if differs how :?: 1) YES.... 2) NO, ideally it should not differ. How can I found the TIMESTAMP value available on DBRM & COBOL O/P AFTER PRECOMPILING You can find DBRM TS in SYSIBM.SYSPLAN table under column "BOUNDTS" and cobol TS can be found in load module.

Every DBA and programmer has experienced the dreaded -818 or -805 error, indicating that the version of the load module you are running doesn't match the version of the package or plan in the DB2 catalog.
Some sample output is shown below: Error level = E, only load module timestamp errors will be printed Dynamic linking specified, module xref table will not be built Reading package details from catalog Running timestamp comparison TN10730 No package timestamp matched in load module TN10730 DBRM timestamp does not match any package Load module and DBRM timestamps match TN20250 No package timestamp matched in load module TN20250 DBRM timestamp does not match any package
Load module and DBRM timestamps do not match

I'm using DB2 on mainframe (os390) with cobol & cics. If i add new index, do i need to compile or just rebind the existing programs. If new index is added we dont need to precompile again.As happyraman1 said Rebind is enough.It will get the data from catalog (which already got when bind is done).

Rebind is used when the program has not changed,but authorizations have been changed,or new index have been created etc. Can you give me some useful references for DSNUTILB utility with examples. DSNUTILB is DB2 utilty-run pgm usually coded in a procedure (JCL) here is an example of the above mentionned proc :

Code: //DSNUPROC EXEC PGM=DSNUTILB,REGION=0M, // //STEPLIB //SYSPRINT //UTPRINT PARM=(&SYSTEM,'&UID','&UTPROC') DD DSN=&LIB,DISP=SHR DD SYSOUT=* DD SYSOUT=*

//SYSUDUMP DD SYSOUT=* //* END OF PROC

this utility is used to run checks, reorgs, or image copies. and usually DSN1CPY is used to restore from image copies. use TSO batch monitor pgm (IKJEFT01) to start, display or stop tables.

HERE IS AN EXAMPLE OF INLINE DSUNPROC PROCEDURE FOR IMAGE COPY :

Code: //userid // JOB (USERJOB,DBA),'IMAGE COPY',

MSGLEVEL=(1,1),REGION=6M,NOTIFY=&SYSUID DD DSN=your-db2-lib,DISP=SHR PROC

//JOBLIB //COPY

//DSNUPROC EXEC PGM=DSNUTILB,REGION=0M, // //SYSPRINT PARM=(&SYSTEM,'&UID','&UTPROC') DD SYSOUT=*

//UTPRINT

DD SYSOUT=*

//SYSUDUMP DD SYSOUT=* //SYSC0001 DD DSN=hlq.YR-BKP-FILE, // // // PEND //* //COPY1 EXEC PROC=COPY DISP=(NEW,CATLG),LABEL=(1,SL), UNIT=3490,VOL=(PRIVATE,RETAIN)

//COPY1.SYSIN DD * COPY TABLESPACE YR-TBSPACE-NAME /* DSNUM ALL COPYDDN SYSC0001

dsnutilb IS USED for checks recover and repair the Nth Max sal of an employee I tried this query to find the nth max sal . It worked fine for me.

Quote:

select sal from emp A where n =

( select count(*) from emp B where A.sal < B.sal )

Here replace n with the required number. 1. How do you use MULTIPLE CURSORS for a single table?

Imagine a scenario like this ... A Result Set has 30 Rows returning to the application program. Now I want these things to happen.... (Open Multiple Cursors)

a. FIRST CURSOR should fetch first 10 rows. b. SECOND CURSOR should fetch then next 10 rows (i.e., 11 - 20) c. THIRD CURSOR should fetch the last 10 rows (21 - 30)

Now my question is how do I point to different locations in the Result Set with 3 different Cursors??? Your requirement is non-standard. As per normal processing this can not be done.

Following are the ways to do it:

1) You can use only one cursor and process the specific number of records in paragraphs. say 1 to 15 in Para-1, 16-30 in Para-2 and remaining 15 records in Para-3.

In this way you can direct the processing in your desired manner.

2) The other way to do is as below:

Quote:

a) Get the number of records from the table for the query. SELECT COUNT(*) FROM <TABLE-NAME> WHERE <WHERE-CONDITION>

b) Divide the count by 3 and get the integer records

c) In first Cursor by using FETCH FIRST N ROWS clause fetch the COUNT/3 records in ASCENDING order

d) In third Cursor by using FETCH FIRST N ROWS clause fetch the COUNT/3 records in DESCENDING order (Here the last record will come first and first record will come last)

e) Now that you have first N/3 and last N/3 records there will be middle N/3 records remaining. These records can be retrieved by using the LAST KEY of both the cursors. (Last record's KEY of both the cursors)

SELECT * FROM <TABLE-NAME> WHERE KEY > KEY1 and KEY < KEY3

Here KEY1 = Last record of the first cursor. KEY3 = Last record of third cursor. Code the cursor as below:

Code: DECLARE MYCURSOR CURSOR FOR SELECT COLUMN1, COLUMN2 FROM MYTABLE WHERE MYKEY > :WS-MY-KEY

Initially move LOW-VALUES to WS-MY-KEY.

After every commit, save the key in check point area.

During restart, move the saved key value to WS-MY-KEY and after the open and fetch of the cursor you will have the next record. Imagine your CURSOR updated 200 rows and COMMIT takes place. Then abend occurred at 201215. How u know the number of rows updated by ur cursor and where abend occurred. Now, how u modify ur program w hich donot update the first 200 rows? Code the cursor as below: Code: DECLARE MYCURSOR CURSOR FOR SELECT COLUMN1, COLUMN2 FROM MYTABLE WHERE MYKEY > :WS-MY-KEY

Initially move LOW-VALUES to WS-MY-KEY.

After every commit, save the key in check point area.

During restart, move the saved key value to WS-MY-KEY and after the open and fetch of the cursor you will have the next record. 1. pls let me known about the maximum no of columns& rows that can created in DB2 :?:

2. explain in detail about exist ,Any ,All in subqueries :idea: . 1. Max no of Cols and Rows in a DB2 Table.

the maximum number of columns in a table and the maximum byte size of a row in a table are determined by the page size.

Page Size Row Size Limit Column Count Limit

4K 4 005 500 8K 8 101 1 012 16K 16 239 1 012

32K 32 677 1 012

2. Exists, Any, All

You can use a subquery to test for the existence of a row that satisfies some condition. In this case, the subquery is linked to the outer-level query by the predicate EXISTS or NOT EXISTS.

When you link a subquery to an outer query by an EXISTS predicate, the subquery does not return a value. Rather, the EXISTS predicate is true if the answer set of the subquery contains one or more rows, and false if it contains no rows.

The EXISTS predicate is often used with correlated subqueries. The example below lists the departments that currently have no entries in the PROJECT table:

SELECT DEPTNO, DEPTNAME FROM DEPARTMENT X WHERE NOT EXISTS (SELECT *

FROM PROJECT WHERE DEPTNO = X.DEPTNO) ORDER BY DEPTNO You may connect the EXISTS and NOT EXISTS predicates to other predicates by using AND and OR in the WHERE clause of the outer-level query.

Quantified Predicates All & Any A quantified predicate compares a value with a collection of values. If a fullselect returns more than one value, you must modify the comparison operators in your predicate by attaching the suffix ALL, ANY, or SOME. These suffixes determine how the set of values returned is to be treated in the outer-level predicate. The > comparison operator is used as an example (the remarks below apply to the other operators as well):

expression > ALL (fullselect) The predicate is true if the expression is greater than each individual value returned by the fullselect. If the fullselect returns no values, the predicate is true. The result is false if the specified relationship is false for at least one value. Note that the <>ALL quantified predicate is equivalent to the NOT IN predicate. The following example uses a subquery and a > ALL comparison to find the name and profession of all employees who earn more than all managers:

SELECT LASTNAME, JOB FROM EMPLOYEE WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE WHERE JOB='MANAGER')

expression > ANY (fullselect) The predicate is true if the expression is greater than at least one of the values returned by the fullselect. If the fullselect returns no values, the predicate is false. Note that the =ANY quantified operator is equivalent to the IN predicate.

expression > SOME (fullselect) SOME is synonymous with ANY. 1. Can anyone tell me about what a Image Copy is??

2. What are the types of Image Copies?

3. Diff B/W a Image Copy & Merge Copy? There are two types of image copies: 1. A full image copy is a copy of all pages in a table space, partition, data set, or index space. 2. An incremental image copy is a copy only of pages that have been modified since the last use of the COPY utility.

MERGECOPY: The MERGECOPY online utility merges image copies produced by the COPY utility or inline copies produced by the LOAD or REORG utilities. It can merge several incremental copies of a table space to make one incremental copy. It can also merge incremental copies with a full image copy to make a new full image copy.

1. Can anyone EXPLAIN me with an EXAMPLE, What are ..

a. ON DELETE CASCADE

b. ON DELETE RESTRICT

c. ON DELETE SET TO NULL.

2. Also tell me What is the Action/Reaction to Parnt & Child Tables when an Delete is done on either of these tables.

Actually this DELETE rule is referential constraint.

The DELETE rule defines the effects that deleting a row in the referenced table has on the referencing table The DELETE rule is also used when column attributes are defined.

No DELETE rule: deleting a row in the referenced table will fail if matching rows exist. ON DELETE CASCADE: if a row in the referenced table is deleted, all of the matching rows are deleted. ON DELETE RESTRICT: deleting a row in the referenced table will fails if matching rows exist. ON DELETE SET NULL: if a row in the referenced table is deleted, a NULL value is assigned to each referencing column of every matching row. None of these referencing tables may be a NOT NULL column. 1.what are the differences between vasm and db2. why we r going for db2.

2.function of REBIND option

3.how to access even records(ie record 22, 24, ..... upto 40 from 20) in indexed organization and dynamic access mode using alternate indexes. Quote: 1.what are the differences between vasm and db2. why we r going for db2.

VSAM means virtual storage access methods of storing your data permanantly in DASD.

DB2 is a relational database, which also stores data, but give you a high access control over it.

there is no relation b/w data in a VSAM file, but DB2 provides integirity and entity relationship among data.

Quote: 2.function of REBIND option

REBIND binds your DBRM again without disturbing your base program. You can prefer REBINDING whenever,

a) An INDEX is added to your table b) RUNSTATS utility has been run

Always prefer rebinding, instead of bind, whenver any authorization changes have been made to the table, but not any SQL statements in your program.

Quote: 3.how to access even records(ie record 22, 24, ..... upto 40 from 20) in indexed organization and dynamic access mode using alternate indexes.

Begin with your START commend with indexed from 20NTH RECORD. Use READ NEXT commend twise. Display the second READ NEXT valued. It will give you all even records. Perform this loop 10 times. What r the Locking types in DB2? Explain? Exclusive Share Update Intent

Exclusive - only one user can read/write/update Share - Only one user can update/write. Others r allowed to read Update - (i will get u that later) Intent - These r like indicators. If a job is using some table say "A" and other job want to access the same. This lock jus says about the status of the table. That is it gives information about which job is currently using that and for what sort of operation and all related stuff. Intent locks r further classified into different categories. concept of correleted subqueries and sibqueries with suitable examples. Definition: A correlated subquery refers to at least one column of the outer query.

Any predicate that contains a correlated subquery is a stage 2 predicate.

Example: In the following query, the correlation name, X, illustrates the subquery's reference to the outer query block.

SELECT * FROM DSN8610.EMP X WHERE JOB = 'DESIGNER' AND EXISTS (SELECT 1 FROM DSN8610.PROJ WHERE DEPTNO = X.WORKDEPT AND MAJPROJ = 'MA2100');

What DB2 does: A correlated subquery is evaluated for each qualified row of the outer query that is referred to. In executing the example, DB2:

1. Reads a row from table EMP where JOB='DESIGNER'.

2. Searches for the value of WORKDEPT from that row, in a table stored in memory.

The in-memory table saves executions of the subquery. If the subquery has already been executed with the value of WORKDEPT, the result of the subquery is in the table and DB2 does not execute it again for the current row. Instead, DB2 can skip to step 5.

3. Executes the subquery, if the value of WORKDEPT is not in memory. That requires searching the PROJ table to check whether there is any project, where MAJPROJ is 'MA2100', for which the current WORKDEPT is responsible.

4. Stores the value of WORKDEPT and the result of the subquery in memory.

5. Returns the values of the current row of EMP to the application.

DB2 repeats this whole process for each qualified row of the EMP table.

Notes on the in-memory table: The in-memory table is applicable if the operator of the predicate that contains the subquery is one of the following operators:

<, <=, >, >=, =, <>, EXISTS, NOT EXISTS

The table is not used, however, if:

There are more than 16 correlated columns in the subquery

The sum of the lengths of the correlated columns is more than 256 bytes

There is a unique index on a subset of the correlated columns of a table from the outer query 1. Is there any command to alter the existing structure (modify column width in table structure)

2. How do we select the first row only in table?

3. Can we have ROWNUM, ROWID in DB2

4. Can we have NVL function in DB2.

5. What are functions in DB2 available? 1. Is there any command to alter the existing structure (modify column width in table structure)

there is no direct command like alter with modify in sql,

U may alter table struture using QMF.

2. How do we select the first row only in table?

Use cursor with "FOR FETCH 1 ROW ONLY"

3. Can we have ROWNUM, ROWID in DB2 We have ROWID, but not ROWNUM

4. Can we have NVL function in DB2. We have NULL, No NVL

5. What are functions in DB2 available? max,min,avg,sqrt,etc.,,,,, ans 2. WE use query ex:SELECT * from tabname ORDER BY fldname FETCH FIRST 1 ROW ONLY; 1. Is there any command to alter the existing structure (modify column width in table structure)

Ans: Yes, we can use ALTER TABLE command to modify the structure of a DB2 table. the syntax is as follows...

- to modify type or width of a column ALTER TABLE <TABLE> MODIFY(COL1 TYPE(WIDTH),.....);

- to add new column

ALTER TABLE <TABLE> ADD(COL1 TYPE(WIDTH),.....);

- to drop a column ( only in DB2 Ver. 8.2 or higher)

ALTER TABLE <TABLE> DROP COLUMN <NAME>;

2. How do we select the first row only in table?

Ans: SELECT * FROM <TABLE> FETCH FIRST 1 ROW ONLY;

3. Can we have ROWNUM, ROWID in DB2

Ans: ROWID function returns a unique row id assigned to a row. It is different from System to system.

4. Can we have NVL function in DB2.

Ans: We dont have NVL function in DB2. But we have the COALESCE function, which returns the value of the first nonnull expression. i.e. consider a table in which i have salary and comm columns. I want to find out gross (sal+comm). But comm is null for some rows, where we didnt get the result. We can substitute 0 in the place of null. select sal+COALESCE(comm,0) from emp;

5. What are functions in DB2 available?

Ans: Lot of functions are available in DB2. They are...

- CHARACTER FUNCTIONS - NUMBER FUNCTIONS

- AGGREGATE OR GROUP FUNCTIONS - DATE FUNCTIONS - CONVERSION FUNCTIONS The ALTER TABLE statement modifies existing tables by:

- Adding one or more columns to a table - Adding or dropping a primary key - Adding or dropping one or more unique or referential constraints - Adding or dropping one or more check constraint definitions - Altering the length of a VARCHAR column - Altering a reference type column to add a scope - Altering the generation expression of a generated column - Adding or dropping a partitioning key - Changing table attributes such as the data capture option, pctfree, lock size, or append mode. - Setting the table to not logged initially state.

We can change the width of the VARCHAR column as follows...

ALTER TABLE <TABLE> SET <COLUMNNAME> DATA TYPE VARCHAR(NEWWIDTH); Can anybody explain about the DB2 Connection, DB2 Entry, DB2 Transaction. DB2 Connection is to have CAF to get connected with DB2

DB2 Entry is have the entry for plan,

DB2 Transaction is to relate the DB2 Entry with the application program Transation ID. These entries will be registered in RCT

the difference between collection and plan. How they r used ? Collection is a set of packages.

Package is the executable access path code for the sql statements in the DBRM

Plan contains package list which is nothing but pointers to packages.

Here i give you some more information which clearly says you the use of plan,package and collection.

We can BIND the instructions for the SQL that was in the DBRM into a PLAN (the old way), or We can BIND the instructions into a PACKAGE (this also become old now).But binding the instructions into a plan works fine as long as the program will be standalone pgm.It has many drawbacks.After that we started binding instructions into a package

If only one DBRM could be bound into a PACKAGE, and if PGMA need to CALL PGMB and PGMB need to CALL PGMC etc etc., then a structure was needed to gather all of the PACKAGEs into a searchable list. This structure became a packagelist, rather than a memberlist, bound into a PLAN.

To solve a few more problems, IBM introduced the concept of COLLECTIONs. A collection is simply a way of grouping packages into meaningful groups. you could use COLLECTIONs to separate programs for different application areas, such as payroll and inventory.

Hence program bound into the COLLECTION will be accessible by the named PLAN. what is the differance between QMF and SPUFI. In SPUFI result of the query will be in PS or in PDS member will store but In QMF result of the query u can not store. The biggest difference between QMF and SPUFI is that QMF is a query/reporting environment with the ability to format reports. SPUFI is just a quick and dirty SQL execution engine. If you need to produce nice looking reports, enable user

input to a query, or store your queries and reports for future usage, QMF is a much bSPUFI :

1.you can execute more queries at a time. 2.you know the sqlcode after executing the query.

QMF: 1.you cannot execute more than one query. 2.you can't know the sqlcode of the query. etter technology for doing so.

explain how rebind is done in DB2. If there is a time stamp mismatch error how is it solved. This REBIND does the same as BIND with the difference that it uses the sql statements that were saved in the catalog during the previous BIND,whereas BIND uses the DBRM(external) statements.

AFAIK this rebind is used when the program has not changed,but authorizations have been changed,or new index have been created etc.It is even faster than bind since it is using catalog as input. if rebind has to be done , how is it done practically. REBIND can be done just like BIND.if you go to DB2I PRIMARY OPTION MENU there is an option for REBIND like BIND right 1.diff. between Repeatable Read(RR) and Cursor Steablity(CS)

2.what is TWO PHASE COMMIT.

3. hoe to see the alternative rows of a table(ie 1,3,5,7,etc). 1) Diff. between Repeatable Read(RR) and Cursor Steablity(CS)

2) TWO PHASE COMMIT This occurs when a programmer Issues a Exec CICS Syncpoint command. This is called two phase because CICS will first commit changes to the resources under its control like VSAM files and the DB2 changes are committed. Usually CICS signals DB2 to complete the next phase and release all the locks.

3) Display alternate rows of a table FOR ODD NUMBERS (1,3,5,7,....)

SELECT E, EMP.* FROM (SELECT ROWNUM E, EMP.* FROM EMP) EMP WHERE MOD(E,2)=1

FOR EVEN NUMBERS(2,4,6,8,.....)

SELECT E, EMP.* FROM (SELECT ROWNUM E, EMP.* FROM EMP) EMP WHERE MOD(E,2)=0

1) how to retrieve first n records in a table for example first 5 records

in oracle we hve a option called rowid but in db2 i hve no idea. how can we retrieve??

2) how can we retrieve rows frm centre i.e frm 9th rec to 14th rec ( is it possible in db2)

3) can anyone explain the db2 precompiler process? (such as bind,package,collection,dbrm,runtime supervisor, buffer mgr)

1) ans: we can retrive the first n recors by FETCH FIRST option.

query: select * from table-name FETCH FIRST n ROWS ONLY After Precompilation the output is new source cobol list and DBRM.

DBRM is the collection of SQL statements.

Plan is the compiled form of SQL statements. It contains the optimum path to execute that SQL statements.

Plan is two types one is BIND PLAN and another one is BIND PACKAGE.

FOR BIND PLAN THE INPUT IS MORE THAN ONE DBRM.I.E. PACKAGES...

FOR PACKAGE THE INPUT IS ONLY ONE DBRM.

PLAN IS THE COMPILE FORM OF MORE THAN ONE DBRM. IT MAY BE ONE. i have 100 record in table but i am not declared in primary key how to delete duplicate rows in table

delete from table a where 1!=(select count(*) from table b where b.col1=a.col1 and b.col2=a.col2 and b.col3=a.col3 and ......) explain db2 precompiler process. The first stage is the precompilation step where the cobol program with the embedded SQL will be modified to form the modified source code and also the DBRM. The DBRM contains the sql statements. The timestamp is also alloted here, the information remains with both DBRM and the modified source code. In the modified source code the sql statemements will be replaced by call to DSNHLI statements with some 5 parameters. These are

1. The DBRM name. 2. SQL statement numbers. 3. The timestamp information. 4. Address info of SQLCA 5. Address info of host variables.

The DBRM undergoes the bind process and package is created. The package is not an executable so we make use of plan. The plan contains pointers to packages.

The modified source code is compiled , link edited to form load module. Then the timestamp is matched with the info in package. If mismatch is there we get timestamp mismatch error and rebind has to be done with proper DBRM. error -818 Time Stamp error , because the time stamp value in your PLAN/PACKAGE and in your program doesn't match.

This problem can occur if you:

1. Precompile, compile, and link, without doing a BIND of the application, 2. Precompile and BIND, without doing the compile and link for the application program, or 3. BIND the application using a DBRM that resulted from a different precompile of the application program than that which produced the object module that is linked into the application module. 1) whatz null indicator variable?

2) whatz use of db2 utilities? (real time)

such as load, quisce, copy, check data

3) if not null with default is specified during an 'alter' command what will be the default values of date, time, timestamp ?

4) whatz timestamp mismatch error (-818) ?

5) can we use db2's 'like' operator for numeric values? or the operator is meant only for alphabetiv values?

can i give select * from acc-table where acc-no like '989%' 1. Null Indicator: used by DB2 to specify whether a column contains null or not null values. if the value of Null indicator is 0 then NOT NULL. If -1 then Null and -2 Truncated.

If u need some more informations i can provide.

4. -818 - The Precompiler generated timestamp X in the load module is different from bind Time stamp Y in DBRM. Recompile it again to solve the problem.

5. Like operators can only be used for Alphabets I suppose. eg:

1. select * from emp where empname LIKE 'A%'

It will take the names of the employees starting with alphabet A .

2. Select * from emp where empname LIKE '-AM%'

It will take the only employee names having 2nd and 3rd letter as AM . SELECT MIN(SALARY) FROM TABLE.EMP WHERE EMPNO = '1025' ;

In case there is no EMPNO '1025' then what would be the O/P

(i) NULL (i) SQLCODE of +100

Q-2 : I have the following two queries

1. SELECT DEPTNAME, AVG(SALARY) FROM TABLE.EMP GROUP BY DEPTNAME;

2. SELECT DEPTNAME, SUM(SALARY)/COUNT(*) FROM TABLE.EMP GROUP BY DEPTNAME;

(i) The output of both the queries would be same. (ii) The output of both the queries would not be same. (iii) The output of both the queries may or maynot be the same.

Q-3: From the following table write down the query to count the department numbers.

EMPNO WORKDEPT

1000 SALES 1001 ACCTS 1002 SALES 1003 ACCTS 1004 ACCTS 1005 ADMIN 1006 SALES 1007 ADMIN 1008 ADMIN 1009 MKETG 1010 SALES 1011 MKETG 1012 MKETG

Ans-1 : NULL

Ans-2 : (iii) In theory Avg means SUM divided by count but it maynot return the same value b'cos SUM would ignore nulls but the count function would count all the values regardless of nulls. The AVG function just works on the numeric arguments.

Ans-3 :

SELECT COUNT(DISTINCT WORKDEPT) FROM TABLE.EMP; how to capture and test that the column is Null in Cobol Program. by a null indicator variable. If the indicator variable is -1 then the filed is NULL else it is not null

Code:

EXEC SQL SELECT NAME INTO :NAME INDICATOR :NAME-IND FROM <table name> WHERE ID = 10 END-EXEC. IF NAME-IND = -1 DISPLAY "NULL ELSE DISPLAY "NOT NULL".

where NAME AND NAME-IND are host variable to be declared in WS section

1) while compling cobol-db2 program what stands for

my prog() dsn system()

and where actually we will be giving program name.

2)can planname and program name can be same.

3)if have 10 sql stmts and after precmpliation we get 10 call stmts and my doubts is how many dbrms will be produced whether only one or 10 dbrms 1) while compling cobol-db2 program what stands for

my prog() dsn system()

My Program used to specify your program name. DSN youd to specify the DB2 sub system name.

Quote: can planname and program name can be same.

Yes, Plan name, DBRM Name, Program name, Even Load module name also may be same.

Quote: )if have 10 sql stmts and after precmpliation we get 10 call stmts and my doubts is how many dbrms will be produced whether only one or 10 dbrms

Pre-Compiler will create ONLY ONE DBRM, even if you have thousands of SQL queries in your program. 1.Max how many coloms can exist in a table 2.in create index maxhow many coloms i can specify 3.max how many composite primarys i can create for a single table 4.how many records i can store in single table 5.max how many coloms i can specify while using select statement

How to code the PARM parameter in a JCL which executes a DB2 program. //... //SYSTSIN DD * DSN SYSTEM(XXX) RUN PROGRAM(COB-DB2-PGM) PLAN(COB-DB2-PLAN) LIB('PGM.TEST.LOADLIB') PARM('cob-db2-parm') 1) What is index? Diff. types of index (explain) Whatz the use of index? 2) how can we create stored procedures, trigger in db2 (with examples)

3) what is dynamic sql? 4) diff. types of locking. explain ? 5) how can i enable or disable primary or foreign key? (When i use alter it shows error) 6) diff. between QMF and SPUFI? What is index? Diff. types of index (explain) Index is another table which contains the column in ascending/descending order. Unique Index/ Primary index / Non-nique index etc... Quote: What's the use of index? To search the table more efficiantly Quote: what is dynamic sql? If you know the SQL statements at compile time it's static SQL, at Runtime it's Dynamic SQL. Quote: diff. types of locking. explain ? Locking row level, page level, table level & table spce level available. Quote: how can i enable or disable primary or foreign key? ALTER TABLE EMP DROP PRIMARY KEY. ALTER TABLE EMP ADD PRIMARY KEY(empno) Quote: diff. between QMF and SPUFI? QMF - Query Management Facility SPUFI - SQL processor Using File Input In SPUFI you should create two data sets to provide & view I/O In QMF data sets not necessary. In QMF you can generate & print reports. in SPUFI not like that.

1) if NOT NULL WITH DEFAULT is specified for Date, Time and Timestamp field, what will be the default value if we left blank ? 2) Give 2 tables T1 and T2 T1 T2 A1 B2 3 u make a query SELECT * FROM T1,T2 what is the no. of rows that are fetched from this query ? 3) Who is the database manager of db2? 4) Runtime supervisor, buffer manager (function) 1) if not null with Default is specified for Date time and timestampt the DATE and Time at the time of LOAD or INSERT or Update will be updated 2) for Select * from T1,T2 if T1 has 3 rows and T2 has 2 rows the query will result in 6 rows Does anyone knows how to check the version of DB2 in s/390??? In the ISPF/PDF PRIMARY OPTION MENU Type U.FD and Press ENTER Now Type OPTION ===> 0 and Press Enter Now right side of the screen you can find out the DB2 Version as DB2 Version: 7.1.1 FADB2 Version: 4.6.1.10

what data that a db2 node lock file contains? Any DB command log contains a list of commands executed, whether committed or not, the session parameters, user/tablespace access traces, pre/post images of records updated.... how COMP, COMP-3 values get stored in DB2. For SQL declaration of DECIMAL(n,m), the COBOL equivalent generated is PIC S9(n-m)v9(m) COMP-3 can v insert a column in a table, is it possible to insert a column in the middle of the table?

We can add a new column using ALTER TABLE but not in the middle. We can do it by using one indirect method that is... for example i have a table EMP with following columns EMPNO,ENAME,JOB,DOB,DEPTNO You want to insert a column SAL between JOB and DOB then apply the following steps... ALTER TABLE EMP ADD COLUMN SAL NUMBER(5,2); this will add SAL column at end. then create a view as follows... CREATE VIEW EMPVIEW AS SELECT EMPNO,ENAME,JOB,SAL,DOB,DEPTNO; and use the view instead of table q1. Can a table have more then one primary key. q2 . What is the diff. between unique key and primary key. q3. is it necessary to creat a index for every table. q4.Can a table resides under more then one tablespace . 1) Ans. One table should have only one primary key. 2) Ans. The main difference b/t unique key and primary key is null value. Unique key may have null value. 3) Ans. If no index exists means you will not able execute some functions like count etc. To create path you need the index. If no index means there is no difference between flat file and database file.. 4) no table can reside in more than one table space. -104 -illegal characters found in the query. (the column length is more than 18 characters. etc )

difference b/w primary key and unique key. The main Difference is that Primary key means ----- No Duplicates and No Nulls. Unique key means ------ No Duplicates but Allows Nulls. I need to change the primary key for an already existing DB2 table . My doubt is if I change the primary key using the Alter table command , do the index for this new key will be generated or not ? . Now after the

alteration how will the Select statements on this table work .. ?will it be using the new Key while selection. first step is to identify the list of programs where the impacted DB2 table is used. Second is to analyse what kind of DDL statements used in each of the program and create a report of it. If the new filed, is not going to be a part of Index, then Delete/Update statements will not be affected. Insert/Select will be impacted based on the usage of the filed Take an image copy of the table. Drop the table Create a new table defination Load the table from the previous image copy /* here the format differs so you may use one time program to load this, otherwise you can chagne the syspunch and load*/ now you need to modify the impacted program. Compile, link-edit and bind all the programs where the table is used. can anyone tell , in my db2-cobol prgm i will make a modification in my cobol prgm but i will not make any changes to my embedded SQL stmt . so, to run this db2-cobol pgm what are all the things i should take care? if i just compile & link edit, time stamp missmatch will occur right ?so how u will fix this? or alse should i precomplie || compile bind | || link edit plan || load mod u need to do all the things again. precomplie,complie,bind,link edit 1. i have a varchar of x(10) but in the length i move 10,but in text i give "ans" ,what will be the output 2. how to avoid -913 errror 1. The output will be ans 2.The application should either commit or roll back to the previous COMMIT. Then, in general, the application should terminate. See message DSNT376I for possible ways to avoid future deadlocks or timeouts.For more information about how CICS, and TSO handle deadlocks

Can any one please tell me the best optimum query to find nth highest salary? SELECT SAL FROM TABLEA A WHERE N=(SELECT COUNT(DISTINT *) FROM TABLEA B WHERE A.SAL<=B.SAL); FOR TOP N SALARIES JUST CHANGE CONDITION AS N<= INSTEAD OF N=. wat's the difference b/w view,alias and synonym? 1.A synonym is used to reference a table or view by another name. The other name can then be written in the application code pointing to test tables in the development stage and to production entities when the code is migrated.The synonym is linked to the AUTHID that created it. CREATE [PUBLIC] SYNONYM tabspaces FOR sys.dba_tablespaces 2. Views are virtual tables that is, they are collections of columns from related tables that are defined in a way such that they make it easier for a user to access needed information from a database. For example, a salesperson may be accustomed to viewing sales orders according to the traditional sales order form that the firm uses. In most firms, the sales order requires data from the CUSTOMERS, ORDERS, ORDERLINE, and PRODUCTS tables. 3. An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. The alias is not dropped when the table is dropped. how to select nth row from table. SELECT * FROM TEST.TABLE1 T1 WHERE 5 = ( SELECT COUNT(DISTINCT T2.NUM) FROM TEST.TABLE2 T2 WHERE T2.NUM >= T1.NUM) ORDER BY NUM DESC ;; what will be the result of below query select '1' ,empno from emptable where ssn= 000010 the table has empid,empno,ssn fields what does is mean giving literals in a query ( '1') Suppose the emptable has rows like: 10 200 000010

20 400 000020 then the result of the query is: 1 200 000010 How can i find second max salary from a table SELECT MAX(SALARY) FROM EMPTABLE WHERE SALARY < (SELECT MAX(SALARY) FROM EMPTABLE) ; To find the SECOND MINIMUM salary: SELECT MIN(SALARY) FROM EMPTABLE WHERE SALARY > (SELECT MIN(SALARY) FROM EMPTABLE) ; To find the Nth MAXIMUM SALARY of the table: SELECT SALARY FROM EMPTABLE A WHERE (N-1) IN (SELECT COUNT(*) FROM EMPTABLE B WHERE A.SALARY > B. SALARY) In a table , there are 25 records .Its not in the order.I want to display the last three records as it is in the table. Don't want to sort.how to write a query for this ?. Cursors with "FOR FETCH LAST 3 ROWS ONLY" option. USE A SENSITIVE STATIC SCROLL CURSOR WHERE YOU HAVE THE OPTION OF RETRIVING THE RECORDS AS YOU WANT FETCH LAST FETCH NEXT FETCH PRIOR.............

How many nested Queries at maximum can a Select statement can have? At the max you can have 15 nested queries, and total of 16 queries in a select statment. How many Maximum no. of columns can a DB2 table can have? For this i have mentioned that u can have at the max 224 columns during the earlier posts. go through the posts, and see that you are not repeating the queries.

how to open a empty VSAM file?Is it possible to open?. its not possible to open a empty VSAM file. will throw an error which authority can be granted to group of users using the GRANT stmt? Granting Privileges The GRANT statement allows an authorized user to grant privileges. A privilege can be granted to one or more authorization names in one statement; or to PUBLIC, which makes the privileges available to all users. Note that an authorization name can be either an individual user or a group. On operating systems where users and groups exist with the same name, you should specify whether you are granting the privilege to the user or group. Both the GRANT and REVOKE statements support the keywords USER and GROUP. If these optional keywords are not used, the database manager checks the operating system security facility to determine whether the authorization name identifies a user or a group. If the authorization name could be both a user and a group, an error is returned. The following example grants SELECT privileges on the EMPLOYEE table to the user HERON: GRANT SELECT ON EMPLOYEE TO USER HERON The following example grants SELECT privileges on the EMPLOYEE table to the group HERON: GRANT SELECT ON EMPLOYEE TO GROUP HERON To grant privileges on most database objects, the user must have SYSADM authority, DBADM authority, or CONTROL privilege on that object; or, the user must hold the privilege WITH GRANT OPTION. Privileges can be granted only on existing objects. To grant CONTROL privilege to someone else, the user must have SYSADM or DBADM authority. To grant DBADM authority, the user must have SYSADM authority. Refer to the SQL Reference for more information about the GRANT statement. How to know when the table data was last updated and who updated that. can get this information from SYSIBM.SYSTABLES difference between Aliases and Synonyms in detail. 1. You need SYSADM or SYSCTRL authority or the CREATE ALIAS privilege to define an alias. No authorization is required to define a synonym. 2. An alias can be defined on the name of a table or view, including tables and views that are not at the current server. A synonym can only be defined on the

name of a table or view at the current server. 3. An alias can be defined on an undefined name. A synonym can only be defined on the name of an existing table or view. 4. Dropping a table or view has no effect on its aliases. But dropping a table or view does drop its synonyms. 5. An alias is a qualified name that can be used by any authorization ID. A synonym is an unqualified name that can only be used by the authorization ID that created it. 6. An alias defined at one DB2 subsystem can be used at another DB2 subsystem. A synonym can only be used at the DB2 subsystem where it is defined. 7. When an alias is used, an error occurs if the name that it designates is undefined or is the name of an alias at the current server. (The alias can represent another alias at a different server, which can represent yet another alias at yet another server as long as eventually a referenced alias represents a table or view.) When a synonym is used, this error cannot occur. What is Correlated Subquery ? Correlated sub query is a type of sub query in which Outer Query is executed at once (fetches one row) and by taking that values inner query will be executed for all rows. Then outer query fetches 2nd row then inner query will be executed for all rows and so on. To clearly under stand see the following example which finds nth max sal SELECT SAL FROM EMP A WHERE N = (SELECT COUNT(*) FROM EMP B WHERE A.SAL<=B.SAL); Outer Query fetches 1 row and inner query compares it with all salaries. Then outer query fetches 2nd row and so on. where actualy a plan is stored stored in SYSIBM.SYSPLANS table and you can access these details by using the select statement. which one has highest precedence in PLAN&PACKAGE 1. When you use packages, you do not need to bind the entire plan again when you change one SQL statement. You need to bind only the package associated with the changed SQL statement. 2. Binding packages into package collections allows you to add packages to an existing application plan without having to bind the entire plan again. A collection is a group of associated packages. If you include a collection name in the package list when you bind a plan, any package in the collection

becomes available to the plan. The collection can even be empty when you first bind the plan. Later, you can add packages to the collection, and drop or replace existing packages, without binding the plan again. 3. Maintaining several versions of a plan without using packages requires a separate plan for each version, and therefore separate plan names and RUN commands. Isolating separate versions of a program into packages requires only one plan and helps to simplify program migration and fallback. For example, you can maintain separate development, test, and production levels of a program by binding each level of the program as a separate version of a package, all within a single plan. 4. The options of BIND PLAN apply to all DBRMs bound directly to the plan. The options of BIND PACKAGE apply only to the single DBRM bound to that package. The package options need not all be the same as the plan options, and they need not be the same as the options for other packages used by the same plan. 5. You can use a bind option to name a qualifier for the unqualified object names in SQL statements in a plan or package. By using packages, you can use different qualifiers for SQL statements in different parts of your application. By rebinding, you can redirect your SQL statements, for example, from a test table to a production table. advantages of stored procedures Stored procedures can encapsulate many of your application's SQL statements into a single message to the DB2 server, reducing network traffic to a single send and receive operation for a series of SQL statements. Stored procedures allow static SQL authorization from a dynamic environment. Stored procedures remove SQL applications from the workstation, which prevents workstation users from manipulating the contents of sensitive SQL statements and host variables. execute the stored procedures.(process involved). Write a stored procedure program that can execute the necessary SQL statements. If your stored procedure is a COBOL program, you must compile it with the option NODYNAM. Write the application program used to CALL the procedure. Bind a package for the stored procedure. Stored procedures require only a package at the server. You do not need to bind a plan. Bind a Plan for the calling application Program. Define the stored procedure in the catalog table SYSIBM.SYSPROCEDURES.

Use GRANT EXECUTE to authorize the appropriate users to use the stored procedure. An Example of CREATE PROCEDURE Statement: Quote: The name is B. It takes two parameters: - An integer input parameter named V1 - A character output parameter of length 9 named V2 It is written in the C language. It contains no SQL statements. The same input always produces the same output. The load module name is SUMMOD. The package collection name is SUMCOLL. It should run for no more than 900 CPU service units. The parameters can have null values. It should be deleted from memory when it completes. The Language Environment run-time options it needs are: MSGFILE(OUTFILE),RPTSTG(ON),RPTOPTS(ON) It is part of the WLM application environment named PAYROLL. It runs as a main program. It does not access non-DB2 resources, so it does not need a special RACF environment. It can return at most 10 result sets. When control returns to the client program, DB2 should not commit updates automatically. This CREATE PROCEDURE statement defines the stored procedure to DB2: CREATE PROCEDURE B(IN V1 INTEGER, OUT V2 CHAR(9)) LANGUAGE C

DETERMINISTIC NO SQL EXTERNAL NAME SUMMOD COLLID SUMCOLL ASUTIME LIMIT 900 PARAMETER STYLE GENERAL WITH NULLS STAY RESIDENT NO RUN OPTIONS 'MSGFILE(OUTFILE),RPTSTG(ON),RPTOPTS(ON)' WLM ENVIRONMENT PAYROLL PROGRAM TYPE MAIN SECURITY DB2 DYNAMIC RESULT SETS 10 COMMIT ON RETURN NO; WHETHER STORED PROCEDURES WILL OCCUPY SPACE OR NOT If it's an Interview question, then the answer is "Yes". in Table empName char(20) but ii is necessary to make is char(30),how?
ALTER TABLE EMP ATLER COLUMN EMPNAME SET DATA TYPE CHAR(30)

Advantages of Packages over Plan: Code: 1. When you use packages, you do not need to bind the entire plan again when you change one SQL statement. You need to bind only the package associated with the changed SQL statement. 2. Binding packages into package collections allows you to add packages to an existing application plan without having to bind the entire plan again. A collection is a group of associated packages. If you include a collection name in the package list when you bind a plan, any package in the collection becomes available to the plan. The collection can even be empty when you first bind the plan. Later, you can add packages to the collection, and drop or replace existing packages, without binding the plan again. 3. Maintaining several versions of a plan without using packages requires a separate plan for each version, and therefore separate plan names and RUN commands. Isolating separate versions of a program into packages requires only one plan and helps to simplify program migration and fallback. For example, you can maintain separate development, test, and production levels of a program by binding each level of the program as a separate version of a package, all within a single plan. 4. The options of BIND PLAN apply to all DBRMs bound directly to the plan. The options of BIND PACKAGE apply only to the single DBRM bound to that package. The package options need not all be the same as the plan options, and they need not be the same as the options for other packages used by the same plan.

5. You can use a bind option to name a qualifier for the unqualified object names in SQL statements in a plan or package. By using packages, you can use different qualifiers for SQL statements in different parts of your application. By rebinding, you can redirect your SQL statements, for example, from a test table to a production table. 1) I am provided with two columns TRAN_DATE,BALANCE for a table which has the bank balance for an ATM user on each day from january to march25.I want to find the average of the bank balance from feb1 to feb 28 in embedded sql,the average bank balance should be transferred to a host variable. 2) I have 5 coloumns for a PAYROLL table .they r ROLLNO,BASIC PAY,HRA,DA,TOTAL_SAL.While creating table i gave WITH DEFAULTS for total_sal & remaining with NOT NULL. ROLLNO is declared as integer while the others r declared as decimal. I want to add the value of BASIC,HRA,DA for each row & update the total_sal which originally has zeroes with the summed up value .What is the query for this. 1 Ans: SELECT AVG(BAL) INTO :HV-AVG WHERE TRAN_DATE >='2005-02-01' AND TRAN_DATE<='2005-02-28'; 2 Ans: UPDATE PAYROLL SET TOTAL_SAL=BASIC+HRA+DA WHERE TOTAL_SAL=0; how can we find out recently updated records in a table? the SQLERRD(3) field of SQLCA,which gives the details of number of rows effected becouse of previous command.... Otherway is in most of the applications we will have a timestamp field in the table or whenever we make any updates to the columns,we also set the timestamp to the current value.... can we redefine host variables yes .but not recommended what is new version in db2 8.2 is the latest version. how do select a first ten rows in a table. SELECT EMPNAME, SALARY FROM EMPLOYEE FETCH FIRST 10 ROWS ONLY; What is the difference between sql syntax checking at precompiled stage to bind stage There is difference between syntax checking in Precompiler and Bind.If delimiters surround an SQL statement, the precompiler does a very basic syntax check to make sure that the column and table names are valid (that they're spelled

correctly and that the columns and the table exist).This validation is not done by DB2 or its CATALOG.The DB2 Precompiler uses the top part of the DCLGEN to validate the SQL syntax. BIND, like precompile, must also check the syntax of the SQL, but the BIND check is more sophisticated. Instead of using the top, DECLARE TABLE portion of the DCLGEN, BIND uses the DB2 CATALOG table information to make sure that the column names are valid, that comparisons are numeric-to-numeric, and so on. This second syntax check occurs because you can't trust the one done by the precompiler because the precompiler check used the DCLGEN What are the possible causes for getting an SQLCODE of -804. 804 AN ERROR WAS FOUND IN THE APPLICATION PROGRAM INPUT PARAMETERS FOR THE SQL STATEMENT, REASON reason Explanation: The call parameter list or the SQLDA is invalid. o The call parameter list, which is created by the precompiler, might be invalid if the application programmer has modified the output of the precompiler, used a variable name beginning with 'SQL' in the application program, or overwritten the call parameter list in some otherway. o The SQLDA, which is created by the application program, has an invalid data type or data length. o The value of SQLDABC is not consistent with the value of SQLD. 01 Open issued for non-cursor. 02 Close issued for non-cursor. 03 Prepare of EXECUTE IMMEDIATE. 04 Statement is not recognized. 05 No statement string present. 06 Bad SQLDA format in parameter list. 07 SQLDA length is invalid. 08 Unrecognized input data type. 09 Invalid length for input variable. 10 Invalid data length for output variable. 11 The value of SQLDABC is not consistent with the value of SQLD. 12 Invalid input data pointer 13 Invalid output data pointer. 14 SQLN has too many items for SQLDABC. 15 Input RDI pointer is invalid. 16 Unrecognized output data type. 17 The value of the 7th byte of SQLDAID is not consistent with the data types contained in the SQLDA. The SQLDA contains a LOB type host variable, but the 7th byte of SQLDAID is not set to '2' or greater to indicate that the extended SQLVARs have been allocated. difference between subquery and correlated subquery SUBQUERY: A query may contain more than one sub query. The inner most query (bottem)

will get executed first, next the higher,so on and at last the first query (top) will be execuited. A non-correlated subquery is the one in which each query is independent of eachother. SELECT EMP_NAME, DEPTNO FROM EMP WHERE EMP_NAME IN (SELECT EMP_NAME FROM DEPT) CORRELATED SUBQUERY: Here for each row of the outer table the inner table will be evaluated and the result if the inner table will be sent one row at a time. That means, there exists corelation between the two tables. See the below example: SELECT EMP_NAME, DEPTNO FROM EMP WHERE EMP_NAME IN (SELECT EMP_NAME FROM DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO) what is 2phase commit in db2? This occurs when a programmer Issues an Exec CICS Syncpoint command. This is called two phase because CICS will first commit changes to the resources under its control like VSAM files. and then DB2 changes are committed. Usually CICS signals DB2 to complete the next phase and releases all the locks.

What's the impact of changing the locksize for tables from the default of ROW to TABLE? row-level locks are better for maximum concurrency than table-level locks. the side effect of lock escalation from row level lock to table level lock is its impact on other applications running concurrently. It may block other applications from accessing the table. For example, if application A holds a shared table lock on a table, it blocks other applications from updating any rows in the table, because they would need to acquire an exclusive lock on a row in that table. Further, it has to be ensured that lock escalation ( Converting row level locks to table level locks by database manager) does not occur for the reasons mentioned above. Inorder to avoid lock escalation it is recommented to practice the foll... . commit your transactions often . If possible, reschedule the applications that compete for access to the same table. Also, use Uncommitted Read [meaning dirty read] transactions where read consistency is not an issue.

Das könnte Ihnen auch gefallen