Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 19

VSAM FILE RETURN CODE

HYPERLINK
"https://www.tutorialbrain.com/mainframe/vsam_file_status/"https://
www.tutorialbrain.com/mainframe/vsam_file_status/

What is the use of partioned tablespace. the term partitioning means the process
of physically dividing data into separate data stores.Create table code to partition
by date
CREATE TABLE orders(id INT, shipdate DATE, …)
PARTITION BY RANGE(shipdate)
(
STARTING '1/1/2006' ENDING '12/31/2006'
EVERY 3 MONTHS
)

Show less

This results in a table being created with four data partitions, each with three
months of data.

Figure 2. Table with 4 data partitions

Will the view update reflects the real table. Yes. The data "in" a view has no
existence independent from the tables that make up the view. The view is, in
essence, a stored SELECT statement that masquerades as a table.

What is with check option in view.To ensure the consistency of the view, you use
the WITH CHECK OPTION clause when you create or modify the view. The WITH
CHECK OPTION is an optional clause of the CREATE VIEW statement. The WITH
CHECK OPTION prevents a view from updating or inserting rows that are not
visible through it.
If we update the view, will it really update base table. Yes. The data "in" a view
has no existence independent from the tables that make up the view. The view is,
in essence, a stored SELECT statement that masquerades as a table. The data is
stored in the original tables and only "assembled" into the view when you want to
look at it.
Which conditions must be satisfied for a view to be updatable?

A view is automatically updatable if it satisfies all of the following conditions: The


view must have exactly one entry in it’s FROM list, which must be a table or
another updatable view. The view definition must not contain WITH , DISTINCT ,
GROUP BY , HAVING , LIMIT , or OFFSET clauses at the top level.

is alternate key should be unique in db2. Alternate keys values should be


unique.We can declare any candidate key as an alternate key. Which means that
the value of this key cannot take duplicate value, however unlike primary key the
primary index is not built on the alternate key.

We can define alternate key while defining any table using a UNIQUE keyword.
For example, if we want to make TRANSACTION_ID as an alternate key then−

CREATE TABLE ORDERS


(ORDER_ID CHAR(15) NOT NULL,
ORDER_DATE DATE,
ORDER_TOTAL DECIMAL(9,2),
TRANSACTION_ID CHAR(15),
PRIMARY KEY(ORDER_ID),
UNIQUE(TRANSACTION_ID))
IN DB4ES01;

can we use join in cursor


Whenever we use JOIN in a cursor on two or more tables (ORDERS and
TRANSACTIONS in this case) a temporary table is generated in the virtual
memory.

Can we use UNION in app. Pgm?


if union is coded in cobol-db2 program cursor declaration is mandatory.
CURSOR Declaration allways ) generate a temporary table is generated in the
virtual memory.

Sample of SELECT with INTO. SELECT INTO statement. The SELECT INTO statement
produces a result table consisting of at most one row, and assigns the values in
that row to host variables.

Examples of count sum distinct date day. Introduction to Db2 SELECT DISTINCT
Sometimes, you want to select distinct values from one or more columns of a
table. To do this, you use the DISTINCT keyword in the HYPERLINK
"https://www.db2tutorial.com/db2-basics/db2-select/"SELECT clause as follows:

SELECT
DISTINCT column_name
FROM
table_name;
Code language: SQL (Structured Query Language) (sql)

The DISTINCT keyword appears after the SELECT keyword but before any column
or expression in the select list. The query above returns distinct values in
the column name from the table_name.

If you have multiple column names listed after the DISTINCT keyword like the
following query:

SELECT
DISTINCT
column_name1,
column_name2, ...
FROM
table_name;
Code language: SQL (Structured Query Language) (sql)

The DISTINCT keyword is applied to all columns. It means that the query will use
the combination of values in all columns to evaluate the distinction.
If you want to select distinct values of some columns in the select list, you should
use the HYPERLINK "https://www.db2tutorial.com/db2-basics/db2-group-
by/"GROUP BY clause.

In case a column contains multiple NULL values, DISTINCT will keep only
one NULL in the result set.

Db2 SELECT DISTINCT examples

We will use the authors table from the HYPERLINK


"https://www.db2tutorial.com/getting-started/db2-sample-database/"sample
database for the demonstration.

1) Using Db2 SELECT DISTINCT with one column


The following query returns all last names of authors from the authors table:

SELECT
last_name
FROM
authors
ORDER BY
last_name;
Code language: SQL (Structured Query Language) (sql)

Here is the result set:

As clearly shown in the output, we had many authors with the same last name
e.g., Abbott, Agans, and Albahari.

To get unique author’s last names, you add the DISTINCT keyword as shown in the
following query:

SELECT DISTINCT
last_name
FROM
authors
ORDER BY
last_name;
Code language: SQL (Structured Query Language) (sql)

Here is the output:

As you can see clearly from the output, the DISTINCT operator keeps one value
for each group of duplicates.

2) Using Db2 SELECT DISTINCT with NULL values


The middle_name column of the authors table contains many rows
with NULL values. When we apply the DISTINCT to the middle_name column, only
one instance of NULL is included in the result set as shown in the result set of the
following query;

SELECT DISTINCT
middle_name
FROM
authors
ORDER BY
middle_name DESC;
Code language: SQL (Structured Query Language) (sql)

Here is the output:

3) Using Db2 SELECT DISTINCT with multiple columns


Let’s set up a new table for the demonstration.

First, HYPERLINK "https://www.db2tutorial.com/db2-basics/db2-create-


table/"create a new table named book_inventories:

CREATE TABLE book_inventories


(
book_id INT NOT NULL,
store_id INT NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY(book_id, store_id)
);
Code language: SQL (Structured Query Language) (sql)

Second, HYPERLINK "https://www.db2tutorial.com/db2-basics/db2-


insert/"insert some rows into the table:

INSERT INTO book_inventories(book_id, store_id, quantity)


VALUES(100, 1, 15);
INSERT INTO book_inventories(book_id, store_id, quantity)
VALUES(100, 2, 20);
INSERT INTO book_inventories(book_id, store_id, quantity)
VALUES(200, 1, 25);
INSERT INTO book_inventories(book_id, store_id, quantity)
VALUES(200, 2, 30);
Code language: SQL (Structured Query Language) (sql)

Third, HYPERLINK "https://www.db2tutorial.com/db2-basics/db2-


select/"query data from the book_inventories table:

SELECT *
FROM book_inventories;
Code language: SQL (Structured Query Language) (sql)

If you use the DISTINCT keyword on the book_id, you will get two values 100 and
200 as shown in the output of the following query:

SELECT DISTINCT
book_id
FROM
book_inventories;
Code language: SQL (Structured Query Language) (sql)

BOOK_ID
-----------
100
200

However, when you add the store_id column to the query as follows:

SELECT DISTINCT
book_id,
store_id
FROM
book_inventories;
Code language: SQL (Structured Query Language) (sql)

BOOK_ID STORE_ID
----------- -----------
100 1
100 2
200 1
200 2

It returns the distinct values of both book_id and store_id.

SYSIBM.

SYSTABAUTH is a DB2 system table which records the privileges that


users/program hold on tables and views. We can use this table to find out the list
of programs accessing a particular table and what action the program is
performing on the table like SELECT, UPDATE, INSERT or DELETE. The below SQL
query can be fired on SYSTABAUTH in order to get list of programs.

SELECT GRANTEE, SELECTAUTH, UPDATEAUTH, INSERTAUTH, DELETEAUTH FROM


SYSIBM.SYSABAUTH
WHERE GRANTEETYPE = ‘P’ AND TNAME = ‘TAB1’
The column SELECTAUTH, UPDATEAUTH, INSERTAUTH and DELETEAUTH
represents SELECT, UPDATE, INSERT and DELETE authority respectively. In the
WHERE clause we will add a GRANTEETYPE predicate as ‘P’ to make sure only
program names are returned (and not the users). We can give the table name
predicate for the TNAME column.

We can find the primary key of any table using the SYSIBM.SYSCOLUMNS table.
The SYSIBM.SYSCOLUMNS is a DB2 system table which contains one row for every
column of each table. It also contains the data related to the views. Below SQL
query can be fired in order to find the primary key of a particular table.

SELECT NAME
FROM
SYSIBM.SYSCOLUMNS
WHERE TBNAME = 'TAB1’
AND KEYSEQ > 0
ORDER BY KEYSEQ ASC;
We will use our table name in the TBNAME column of SYSCOLUMNS table using
the WHERE clause and KEYSEQ > 0 will return only primary keys.

The image copy allows us to download or copy the DB2 table into a mainframe
dataset. There are two types of Image copy i.e. Full image copy and Incremental
image copy. The full image copy is used to take the backup of the entire table. The
incremental image copy refers to the differential backup. In order to take the full
image copy of the DB2 table we can use the below JCL step.

FULL IMAGE COPY JCL

//STEP1 EXEC DSNUPROC


//SYSCOPY DD DSN=TEST.TAB1.COPY,UNIT=SYSDA,VOL=SER=CPY01I,
// SPACE=(CYL,(15,1)),DISP=(NEW,CATLG,CATLG)
//SYSOUT DD SYSOUT=*
//SYSIN DD *
COPY TABLESPACE TAB1SPAC
/*
We can use the utility DSNUPROC for this purpose. The SYSCOPY will have the
dataset in which we want to take the backup of the table. The SYSIN is populated
with the parameter COPY TABLESPACE which is followed by the name of
tablespace where the table TAB1 resides.
FAST LOAD for Z/OS 20 - This scenario explains how to create an image copy as
part of the load process.

As a Database Administrator, you are often asked to load large amounts of data
into Db2 tables. Because of the sheer volume of data that you process, you prefer
to take image copies of the data. That way, if an error occurs you can recover the
data. Fast Load lets you invoke Quick Copy during execution, rather than as a
separate phase. You can specify how many image copies to make, the type of
copies to make, and where to save them.
You can also create image copies before and after the load by calling Quick Copy,
then Fast Load, and then Quick Copy again, in one step.
Using a single job step to invoke both Fast Load and Quick Copy can simplify the
process, decrease processing time, and increase data availability. Fast
Load calls Quick Copy while it rebuilds the indexes, to allow concurrent processing
and decrease processing time. Fast Load also recognizes that the image copies
have been taken. Therefore, it does not set the copy pending flag and place the
table in read-only mode. The table remains in read/write mode, which helps
increase data availability.
You do not need a Quick Copy license to implement this process. Fast Load can
invoke Quick Copy to create your backup image copies. However, you do need a
license to run Quick Copy as a stand-alone utility.
The following illustration shows how a Database Administrator creates an image
copy as part of the load process:

After being asked to load a large amount of data into a table, the Database
Administrator performs the following steps:
(Optional) Specify dynamic allocation settings for the image copy data sets.
Add the QUICKCOPY keyword to your Fast Load job.
How to allocate dynamic ds in JCL?
Dynamic allocation of work data sets
1. If DYNAUTO=IGNWKDD, dynamic allocation takes precedence over JCL
allocation. ...
2. If DYNAUTO=YES, JCL allocation takes precedence over dynamic allocation. ...
3. If DYNAUTO=NO, dynamic allocation of work data sets is not used unless you
specify the DYNALLOC run-time option.}

You can use DSN1COPY to copy data from an image copy of the data sets of a
table space to the data sets of a table space on the same subsystem or another
subsystem.

image copy produces a binary copy of the data, including all the internal db2 data
(like object id, position of data within tablespace, etc.).
Unload contains the data in a more readable way. The data is structured in a way
a load-utility may use it.
image copy means : take a back up of the database, by giving the tablespace info
and schema name into a dataset.

IMAGE COPY
This dataset has the complete info and data of the database for which u have
taken a backup.

similarily there will be a restore jcl for having the dataset as input to load all the
data into the database.

2) LOAD PHASES - https://www.ibm.com/docs/en/db2/11.5?topic=utility-load-


overview

LOAD with REPLACE - Deletes all the rows and loads new data
RESUME - will not remove existing data and add new rows in the table

Analyse
When data is being loaded into a column-organized table, the first phase is
the analyze phase, which is unique to column-organized tables. The analyze phase
occurs only if a column compression dictionary needs to be built, which happens
during a LOAD REPLACE operation
LOAD
During the load phase, data is loaded into the table, and index keys and
table statistics are collected, if necessary. Save points, or points of consistency,
are established at intervals specified through the SAVECOUNT parameter in
the LOAD command. Messages are generated, indicating how many input rows
were successfully loaded at the time of the save point.
Build
During the build phase, indexes are produced based on the index keys
collected during the load phase. The index keys are sorted during the load phase,
and index statistics are collected .The statistics are similar to those collected
through the RUNSTATS command
Delete
During the delete phase, the rows that caused a unique or primary key
violation are removed from the table. These deleted rows are stored in the
load exception table, if one was specified.
Index copy
During the index copy phase, the index data is copied from a system
temporary table space to the original table space. This will only occur if a system
temporary table space was specified for index creation during a load operation
with the READ ACCESS option specified.
RUNSTATS and REORG

RUNSTATS is for collecting indexes and tables statistics information which to


enable the DB2 optimizer to generate efficient access plan. reorgs is for
reorganizing tables and indexes.
RUNSTATS ON TABLE/VIEW object-name

How do you reorg a table?

Procedure
To reorganize the tables with an asterisk in the last column, run the following
command: db2 reorg table table_name. ...
To reorganize a table to match the order of a particular index, run the following
command: db2 reorg table table_name index index_name.
UNLOAD and LOAD - http://mframes.blogspot.com/2013/07/unload-and-load-
db2-table.html
The below JCL shows how to UNLOAD data from one table to a dataset
using IKJEFT01.

//STEP02 EXEC PGM=IKJEFT01,DYNAMNBR=50


//SYSTSPRT DD SYSOUT=$
//SYSPRINT DD SYSOUT=$
//SYSUDUMP DD SYSOUT=$
//SYSTSIN DD DSN=TEST.PROCLIB(UNLD),DISP=SHR
//SYSPUNCH DD DSN=TEST.TABLE.STRTCTURE,
// DISP=(NEW,CATLG,DELETE),
// UNIT=DISK,SPACE=(CYL,(1,1),RLSE)
//SYSREC00 DD DSN=TEST.TABLE.LOAD,
// DISP=(,CATLG,DELETE),
// UNIT=CART,
// DCB=(SYS3.DSCB),LABEL=EXPDT=99000
//SYSIN DD *
SELECT * FROM TST.CLIENT ;
/*
//*
——————
Load the downlaoded data from dataset to test DB2 Table

This JCL shows how we can upload the data from Flat File back to DB2 Table.

//LOADTB EXEC DB2LOAD,LDNM=TBLOAD1,DB2=DB2T


//LOAD.SYSREC00 DD DSN=TEST.TABLE.LOAD,DISP=SHR
//*
//LOAD.SYSIN DD DSN=TEST.TABLE.STRTCTURE,DISP=SHR
//*

DB2LOAD is the utility used to execute the load function.


LDNM=TBLOAD1 :: We can use any name here inplace of TBLOAD1
DB2=DB2T:: indicates a test database region.
TEST.TABLE.LOAD contains the data to be loaded into the table which was
downloaded in the unload step.
LOAD.SYSIN contains the table structure along with additional parameters to load
the table.
like
LOAD DATA REPLACE LOG NO ENFORCE NO INDDN SYSREC00
INTO TABLE TST.CLIENT.
—————————
Common errors encountered while loading a table
UTILITY BATCH MEMORY EXECUTION ABENDED, REASON=X'0B37'

Check the spool for which dataset it is abending with SB37.


Then we need to change the UNIT parameter.
——-
DSNURSIX - KEY COUNT INCONSISTENT FOR SORT-RD PHASE,
Resolution:
1. Increase the SORT datafiles used internally in the load utility.
2. Terminate the UTLITY
use the command -TERM UTIL(UTIL-NAME)
Go to DB2I PRIMARY OPTION MENU -> option 7(DB2 COMMANDS)
3. Restart the load job
———-
ERROR LOADING INDEX, ERROR = X'00E40322' INDEX = Bth00.D4xx30X1
Explnation: The load phase of the load job worked, but the rebuilding index failed.
Resolution:
1.Check the allocations for the index of the table.It must be too small.
We need to increase it, Both primary and seconday quantity for all the index
available for the table.
2. Terminate the utility using the same command -TERM UTIL(UTIL-NAME)
3. restart the load job again.
——————-
ONLINE LOAD
load from emp.ixf of ixf replace into emp_copy
After that, run a select statement to see the result as follows.

select * from emp_copy;

Explanation

In the above example, we use a select statement to see the load command result.

——————-
NULL
https://www.ibm.com/docs/en/db2-for-zos/11?topic=statement-handling-null-
values
- Using the DISTINCT predicate, null values are considered equal.
Null values can be used as a condition in the WHERE and HAVING clauses.The IS
NULL predicate is used to check for null values.
If a column is defined as NOT NULL WITH DEFAULT or if you do not specify NOT
NULL, Db2 stores a default value for a column whenever an insert or load does
not provide a value for that column. If a column is defined as NOT NULL, Db2
does not supply a default value.
- Can null be a default value?
If no default value is declared explicitly, the default value is the null value.
This usually makes sense because a null value can be considered to represent
unknown data. In a table definition, default values are listed after the column
data type.
-GROUP BY treats NULLs as valid values.
- How do you make a column accept NULL values in SQL?
ALTER TABLE table_name ALTER COLUMN column_name DATA_TYPE
[(COLUMN_SIZE)] NULL;
- How do you use NULL values when adding rows to a table?

INSERT INTO WORKER VALUES('SAM','ONTARIO',NULL); INSERT INTO WORKER


VALUES('TIM',NULL,56); INSERT INTO WORKER VALUES(NULL,'CAIRO',43); INSERT
INTO WORKER VALUES(NULL,'MUMBAI',NULL); INSERT INTO WORKER
VALUES(NULL,NULL,NULL);
- Can a column be null?

By default, a column can hold NULL values. The NOT NULL constraint enforces a
column to NOT accept NULL values. This enforces a field to always contain a
value, which means that you cannot insert a new record, or update a record
without adding a value to this field.
-
How to insert null value in DB2?
Procedure
 Define an indicator variable or array for a particular host variable or array.
 Assign a negative value to the indicator variable or array.
 Issue the appropriate INSERT, UPDATE, or MERGE statement with the host
variable or array and its indicator variable or array.
===========
COALESCE is an SQL function that accepts a list of parameters and
returns the first non-NULL value from the list.
For example, SELECT COALESCE(NULL, NULL, 'third_value', 'fourth_value'); returns the
third value because the third value is the first value that isn't null.
In what sequence UPDATE works?
UPDATE takes a table and uses the SET keyword to control what row to change and
what value to set it to. The WHERE keyword checks a condition and, if true, the SET
portion is run and that row is set to the new value. If false, it is not set to the new value
———————————————-
3). Is There any way to check which operation has put the table on pending
status??
HYPERLINK "http://mframes.blogspot.com/2013/07/unload-and-load-db2-
table.html"http://mframes.blogspot.com/2013/07/unload-and-load-db2-
table.html
Yes,We can know this from SYSIBM.SYSCOPY Table.
If we run a query against this table, the ULITY values can help us in determining
the desired operation.
DB27 - SYSCOPY was extended with columns JOBNAME and AUTHID. JOBNAME
contains the name of the job which carried out the recorded utility and AUTHID
contains the userid of who ran the job. Before version 7 it could be a pretty tough
job to find out which job and who carried out a utility, but this is now much
easier.
--------------------
elect tabschema concat '.' concat tabname as table_name,

card as rows,

stats_time

from syscat.tables

order by card desc

Number of rows may be not up to date as it's taken from DB2 statistics. Statistics
must be updated after tables has had many updates, or after reorganizing any of
the tables. You can do it with RUNSTATS command.

You can see when they were last updated for particular table
in stats_time column of this query.

------------

CURSOR with WITH HOLD/FETCH ONLY. For WITH HOLD refer book number 143.
FOR FETCH ONLY - means the cursor is read only, issues different types of locks
and does not allow for update. WITH UR - means instead of retrieving only
committed work, your SELECT or FETCH will also retrieve rows that have not been
committed by other tasks.
WITH HOLD. Whenever we issue a COMMIT statement, all the open cursors will
get closed. This is a very common case when we have to frequently use the
commit statement after a UPDATE while working with a cursor. In this case we
can use the “WITH HOLD” clause during the cursor declaration.
The “WITH HOLD” clause will keep the cursor open even after firing the COMMIT
statement.

Can we move values to NULL column in DB2? Inserting a record with a nullable
column:
• To insert a NULL, move -1 to the null indicator
• To insert a valid value, move 0 to the null indicator

I tried the following query but it added a column at the end of the table.
ALTER table table_name
Add column column_name57 integer
OR
In DB2 IBM i v7r1 you can do it, try on your DB2 version
alter table your-table
add column e_father_name varchar(10) before e_mobile_no
1) Modifying the length & data type of column examples
The following example uses the ALTER TABLE ALTER COLUMN statement to
change the data type of the created_date column from DATE to TIMESTAMP:

ALTER TABLE orders


ALTER COLUMN created_date
SET DATA TYPE TIMESTAMP;
Code language: SQL (Structured Query Language) (sql)

This statement HYPERLINK "https://www.db2tutorial.com/db2-basics/db2-alter-


table-add-column/"adds a new column named note to the orders table:

ALTER TABLE orders


ADD COLUMN note VARCHAR(40);
Code language: SQL (Structured Query Language) (sql)
To increase the length of the note column to 255, you use the following
statement:

ALTER TABLE orders


ALTER COLUMN note
SET DATA TYPE VARCHAR(255);

To view the columns of the orders table, you use the DESCRIBE TABLE command:

DESCRIBE TABLE orders;

Can. We add a new column in the middle of a DB2 table. After DB2 V9, alter can
do this. To check the new column added, use To view the columns of the orders
table, you use the DESCRIBE TABLE command: DESCRIBE TABLE orders;
How do I count columns in db2?

Query to count the number of columns in a table: select count(*) from


user_tab_columns where table_name = 'tablename'; Replace tablename with the
name of the table whose total number of columns you want returned.

18.What is the restriction on using UNION in embedded SQL?


A77) It has to be in a CURSOR.
Type to enter text

You might also like