Saturday 27 July 2013

to check queries that have bad performance

Procedures to do when you need to know what are the queries that have bad     
   performance
An easier way to find queries that have bad performance:
• On Db2 V8 run this query:
db2 "select TOTAL_EXEC_TIME, NUM_EXECUTIONS, substr (STMT_TEXT, 1,500) \
as statement from table(SNAPSHOT_DYN_SQL('<database>', -1)) as \
snap_dyn_sql order by 1 desc,2 desc"
• On Db2 V7 run the snapshot command and then the query:
db2 get snapshot for dynamic sql on ICMNLSDB write to file
db2 "select TOTAL_EXEC_TIME_S, NUM_EXECUTIONS, substr (STMT_TEXT, 1,500) \
as statement from table(SYSFUN.SQLCACHE_SNAPSHOT()) as snap_dyn_sql \
order by 1 desc,2 desc"
After finding out the queries that are taking a long time or the ones that run very often, you can use db2advis to check if you need new indexes using it a query each time:
db2advis -d <db_name> [{-s "sql_statement" | -i <input_file>}]
[-l <disk-limit>] [-t <max_advise_time>] [-h] [-o <output_file>]
Where:
-d <db_name> specifies the name of the database to which a connection is to be established.

-s "sql_statement" specifies the text of a single SQL statement whose indexes are to be advised. The statement must be enclosed by double quotation marks.

-i <input_file> specifies the name of an input file containing one or more SQL statements. Statements must be delimited by semicolons. Comments should have two hyphens at the start of each line. The frequency at which each statement in the workload is to be executed can by changed by inserting the following line into the input file: --#SET FREQUENCY <value>

-l <disk-limit> specifies the maximum number of megabytes available for all indexes in the existing schema. The default value is 20% of the total database size.

-t <max-advise-time> specifies the maximum allowable time, in minutes, to complete the operation. If no value is specified for this option, the operation will continue until it is completed.

-h displays help information.

-o <output_file> saves the script to create the recommended objects in output_file.

Or to investigate one or more slow queries in a production environment:

db2advis -d <db_name> -i <input_file> -o <output_file>

Monday 27 May 2013

Inplace/Online Reorg phases

Online or inplace table reorganization allows the user to reorganize a table while permitting full access to that table. While inplace REORG provides uninterrupted user access to the data, the performance of inplace REORG is slower than classic or offline REORG.

During an inplace table reorganization, the entire table is not reorganized at once. Instead, portions of the table are reorganized incrementally. Data is not copied out to a temporary table space: rows are moved within the existing table object to re-establish clustering, reclaim free spaces, and eliminate overflow rows.

There are four primary phases for inplace table REORG:

  1. SELECT N pages
    During this phase, DB2 selects N pages, where N is the extent size with a minimum of 32 sequential pages for REORG processing.
  2. Vacate the range
    With the N pages selected, inplace table REORG moves all rows within this range to free pages within the table. Each row that is moved leaves behind an RP (REORG pointer) record that contains the RID of the row’s new location. The row is inserted to free pages in the table as a RO (REORG overflow) record that contains the data.
    Once REORG finishes moving a set of rows, it waits for all existing data accesses that are occurring in the table (for example, by currently executing applications) to complete. These existing accesses, called old scanners, use old the RIDs when accessing the table data. Any accesses that start during this waiting period, called new scanners, use the new RIDs to access the data. Once all of the old scanners have completed, REORG cleans up the moved rows, deleting the RP records and converting the RO records to normal records.
  3. Fill the range
    After all rows have been vacated, the rows are written back, in a reorganized format, sorted according to any indexes used, and obeying any PCTFREE restrictions defined. When all the pages in the range are filled, the next N sequential pages are selected in the table, and the process begins again.
  4. Truncate the table
    When all pages in the table have been reorganized, the table will be truncated to reclaim space by default. If the NOTRUNCATE option is specified, the reorganized table is not truncated.

Classic/Offline Reorg Phases

Offline table reorganization uses a shadow copy approach, building a full copy of the table that is being reorganized.

The shadow copy image is built within the table space that the table being reorganized resides in. Optionally, the copy can be built in a system temporary table space if the USE option is specified when issuing the REORG TABLE command.

There are four possible phases in a classic or offline table reorganization:

  1. SORT
    If an index is specified with the REORG TABLE command, or if a clustering index is defined on the table, the rows of the table are first sorted according to that index. If the INDEXSCAN option is specified, an index scan is used to sort the table, otherwise, a table scan sort is used. This phase only applies to a clustering REORG. Space reclaiming reorganizations begin at the build phase.
  2. BUILD
    In this phase, a reorganized copy of the entire table is build, either in the table space that the table being reorganized resides, or in a temporary table space specified with the REORG command.
  3. REPLACE
    In this phase, the original table object is replaced by either copying back from the temporary table space, or by pointing to the newly built object within the table space of the table being reorganized.
  4. RECREATE ALL INDEXES
    All indexes defined on the table are recreated.

You can monitor the progress of the table reorganization and determine which phase the process is currently in using the snapshot monitor or snapshot administrative views.

Online Reorg and Offline Reorg in db2 UDB


Offline reorg :
1. Database will be unavailable during offline reorg. If the db is quiesced then only instance owner will be able perform any operation .. other application will not be able to connect.

2. In offline reorg when we use "use tempspace_name" phrase then actually db2 creates a copy of that table in temp_tablespace by building structure of the table ,,, in second phase db2 starts to copy the data as well in proper way and removes dirty pages.. In last phase once this activity gets completed db2 removed the old table and places the newly organized table in its previous tablespace from temp_tablespace.
If we do not use temp_tablespace then at least double space of the table data size + index size is required to continue the offline reorg.

Online reorg :
In online reorg all application can connect to database .but applications perpormance gets slow.. hence creates lock-waits as well. Here db2 do not need temp_tablespace as db2 part by part reorganizes the table data.. Tables data are moved from one place to another place and leaves a row identifier to mention where the data pages are moved.Clean up only option is useful to clear the dirty pages.

But I personally feel online reorg is not useful for big tables. Most of the time it take s much more time compare to offline reorg timings.

Online reorg is compatible with online database backup...

Please correct me if my understanding is not correct ...

Friday 3 May 2013

DB2 Locking Basics

DB2 Locking basics

In any relational database, in order to maintain consistency among the transaction locks need to be acquired on the resource on which the transaction will be executed. Resource can be a Relational Table, or Rows. Locking provide isolation of resource between transaction thereby providing concurrency between independent transaction. DB2 provides four isolation levels.

  • Uncommitted Read
  • Cursor Stability
  • Read Stability
  • Repeatable Read
  • Currently committed (New in DB 9.7)
In order to utilize the isolation level in the transaction, they can be specified at

1) Statement level (SELECT, DELETE, UPDATE)
eg:- SELECT FROM WITH {UR, CS, RR, RS}

2) At session level
eg:- SET CURRENT ISOLATION = {UR, CS, RR, RS}


Commonly referred LOCKING terms

1) Locks
In order to use any resource, DB2 lock the resource before the transaction can use it.


2) Lock-Wait
If any transaction is requesting lock on a resource, and that resource is currently being held by other transaction, then the application requesting the lock goes into LOCK-WAIT mode until the lock on the resource is released by the primary transaction.

3) Deadlock
If two transaction are waiting on each others resources the the both the transaction goes into deadlock state.

4) Lock Escalation
For each lock acquired on a resource, DB2 maintain that information in DB2 locklist memory component. If the locklistmemory started getting exhausted, DB2 escalate all row level lock to table level lock in order to release memory.

How DB2 locking can be monitored?

1) Monitor switches
2) GET SNAPSHOT command
3) db2pd tool
4) Snapshot monitor SQL administrative routines
5) DB2_CAPTURE_LOCKTIMEOUT ( New in DB2 9.5 locking)
                                    Practical Use of DB2_CAPTURE_LOCKTIMEOUT
6) db2cos scripts
7) db2pdcfg with -catch option
8) Locking event monitor as apposed to Deadlock event monitory (New in DB2 9.7 Locking)

Lock related DB CFG parameter

1) LOCKLIST
2) MAXLOCK
3) LOCKTIMEOUT
4) DLCHKTIME

Lock related registry variable

1) DB2LOCK_TO_RB
2) DB2_KEEPTABLELOCK
3) DB2_MAX_NON_TABLE_LOCKS
4) DB2_EVALUNCOMMITED
5) DB2_SKIPDELETED
6) DB2_SKIPINSERTED

Lock monitoring - to get more details click here

Types of Recovery in Db2

Crash Recovery

It is a type of recovery which bring the database back to the consistent state after unplanned failure
It perform rollback operation of the transaction that were not committed and perform data page externalization for all the committed transactions

If the tablespace is damaged in circular logging database and cannot be made online then in order to start the database it needs to be dropped to start the database else database will not start
If the database is not started, try restarting it using RESTART command
                    db2 "restart database sample"

If there are corrupt tablespace the database restart will fail with SQL0290N error code
Then check the DB2 administration notification file for list of all tablespace that are in DROP PENDING state                       db2 get dbm cfg | grep -i diag
                              cd /home/db2inst1/sqllib/db2dump
                               vi db2inst1.nfy

Try restarting the database with DROP PEDNING clausedb2 "restart database sample drop pending tablespaces(userspace1,tbsp_taba)"

Click here to get more detail on DB2 Crash Recovery

Crash recovery can be automated or can be done manually
Enabling Automated crash recovery
Set DB CFG parameter “autorestart” to “ON”db2 "update db cfg for sample using autorestart on immediate"

Following the failure, DB2 will automatically restore the database to a consistent point by rolling forward and backup the changes from Active log files
Manually performing the Crash recovery
DB CFG parameter “autorestart” is set to “OFF”
Following the failure, “RESTART DATABASE” is issued to perform the crash recoverydb2 "restart database sample"


2)Version Recovery

  • It restores the database from the consistent full offline backup available.
  • Restore from only full offline backup operation is available.
  • Version recovery can be used with circular logging and archival logging database.
  • If the database is enabled for archival logging, then using only the FULL OFFLINE BACKUP of the database with the “WITHOUT ROLLING FORWARD” at the end of the “RESTORE” command can be used to perform version recovery.
  • All the transaction after the last full offline backup are lost in this type of recovery.
  • click here to get more details on DB2 Version Recovery

Version recovery example
Sr. No
Description
Sample DB2 Command
1Check if database is configured for Circular logging. If database is configured for Archival logging this step is not needed.db2 get db cfg for sample | grep -i log
               LOGARCHMETH1 = OFF
2Perform Offline backup of the database-- Deactivate the database
db2 deactivate db sample
-- Check if the database is deactivated. This command check for db2loggr process. If not listed then DB is deactivated
db2pd -edus | grep -i db2lo
-- Perform offline backup of the database
db2 “backup database sample to /backup compress”
3Identify the set of offline backup and determine the recovery pointdb2 “list history backup all for database sample”

Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log  Backup ID
-- --- ------------------ ---- --- ------------ ------------ --------------
 B  D  20110520114322001   F    D  S0000023.LOG S0000023.LOG
----------------------------------------------------------------------------
 Contains 3 tablespace(s):

 00001 SYSCATSPACE
 00002 USERSPACE1
 00003 SYSTOOLSPACE
----------------------------------------------------------------------------
    Comment: DB2 BACKUP SAMPLE OFFLINE
Start Time: 20110520114322
  End Time: 20110520114345
    Status: A
----------------------------------------------------------------------------
 EID: 29 Location: /home/db2inst1/gilroy/bar
4Determine which version of the database is needed using the timestamp displayed from the “LIST HISTORY” command Details captured from previous command
1) Timestamp => 20110520114322001 
2) Backup image location =>/home/db2inst1/gilroy/bar
5.aVersion recovery onCircular Logging Databasedb2 “restore db sample from/home/db2inst1/gilroy/bar taken at20110520114322001 into testdb
5.b.Version recovery onArchival logging databasedb2 “restore db sample from/home/db2inst1/gilroy/bar taken at20110520114322001 into testdb without rolling forward

Redirect Restore

1) Redirect restore of the database using version recovery
a) DB is enable for archival logging.

b) Perform offline backup of the database

Offline backup is needed when the current database has to be redirected restore.(Requires, only the Offline backup image)
Online backup can also be used, but transaction done during the online backup needs to be rollforward(Requires, Online Backup image + Archive/Active Log file)c) Performing recovery of database

Version recovery if offline backup is used
Roll-forward recovery if online backup is usedd) Activate the database



2) Restore a failed Tablespace (Non-SYSCAT)

A) Restore failed tablespace from the available backup imagea) Identify the tablespace that is failed

ADMIN NOTIFICATION FILE
db2pd -tablespace -db sample
b) Restore the tablespace from the available backup image

db2 restore db sample tablespace (userspace1) online
c) Rollforward the tablespace to end of logs

db2 "rollforward db sample to end of logs tablespace(userspace1) online"
d) Optional. Take backup of database or backup of the restored tablespace

B) Backup image is not available for the failed tablespace
a) Identify the tablespace that is failed

ADMIN NOTIFICATION FILE
db2pd -tablespace -db sample
b) Check the create time of the failed tablespace

db2 "select varchar(TBSPACE,40),CREATE_TIME from syscat.tablespaces order by CREATE_TIME desc"
c) Check the available backup image
$==> db2 list history backup all for db <dbname>

Sunday 28 April 2013

DB2 Scripts


Write the following scripts in a .out file, then execute it by issuing the db2 command with option -tvf.

  •  Reorg for all tables

$db2 -x "select 'reorg table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),';'from syscat.tables where type = 'T' " > reorg.out

$db2 -tvf reorg.out

  • Reorgchk for all tables
db2 -x "select 'reorgchk update statistics on table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),';' from \
syscat.tables where type = 'T' " > reorgchk.out

$db2 -tvf reorgchk.out

  •  Runstats for all tables
db2 -x "select 'runstats on table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),' and indexes all;'from \
syscat.tables where type = 'T' " > runstats.out

$db2 -tvf runstats.out


Executing reorg, reorgcheck and runstats for all tables from one specific tablespace.
  • Reorg for all tables from one specifc tablespace
db2 -x "select 'reorg table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),';' \
from syscat.tables where type = 'T' and tbspace='<tablespace_name>'" > reorg.out

$db2 -tvf reorg.out
  •  Reorgchk for all tables from one specifc tablespace
db2 -x "select 'reorgchk update statistics on table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),';' from \
syscat.tables where type = 'T' and tbspace='<tablespace_name>'" > reorgchk.out

$db2 -tvf reorgchk.ou
  • Runstats for all tables from one specifc tablespace
db2 -x "select 'runstats on table',substr(rtrim(tabschema)||'.'||rtrim(tabname),1,50),' and indexes all;'from \
syscat.tables where type = 'T' " > runstas.out

$db2 -tvf runstats.out




Fix Pack Installation—DB2 V9.5 FP



Pre-Installation Task:

               To obtain root id from ServerAdmin prior to start of Migration
              Check out the FileSystem space available
              The new version FP is Uploaded into Path: Fixpak location in the servers
Pre install Steps

1.Disable the crontab
2.db2 get admin cfg >admincfg.out
3 db2licm -l > db2licm_before.txt
4 db2 get dbm cfg > dbmcfg_before.txt
5 db2 get admin cfg > admincfg_before.txt
6 db2 list db directory > dbdir_before.txt
7 db2 list node directory > nodedir_before.txt
8 db2 list dcs directory > dcsdir_before.txt
9 db2 get db cfg for <dbname> > dbcfg_<dbname>_before.txt
10 db2set -all > db2set_before.txt
11 db2 list applications show detail > listapplications_before.txt
12 db2 list tablespaces show detail > tablespaces_<DBname>_before.txt (after connecting to each database)
13) db2look -d <db_name> -e -o <(dbname)_look_before.txt> -l -x -f (after connecting to each database)
14) db2 LIST PACKAGES FOR ALL SHOW DETAIL > packages.before
15) db2 "select * from syscat.bufferpools" > bufferpools.before
16) db2 UPDATE DBM CFG USING diaglevel 4 (make sure that we are updating it back to 3 after the install)

1.db2 force applications all
2.Take the full offline database backups ***

Steps for Installation:

1) Stop of DB2 Process:
  • Make a connection as instance administrator for each instance and execute the following commands:

                               $db2 force applications all
                               $db2 terminate
                               $db2stop
                               $db2licd -end (Must be launch on each node)

  •  Make a connection as DAS administrator (DAS or root) & Go to Execute the following command 
                               $su - <das id>
                               $db2admin stop

      Stop the Fault Monitor Coordinator and the Fault Monitor
  • Login as root and go to /db2/sftw/<instance name> /sqllib/bin and execute the following commnad’s 
                            $./db2fmcu -d
                            $./db2fm -d
                login as instance owner, Verify that the IPC interconnection processes are clean with:
cd  /db2/sftw/<instance name> /sqllib/bin/

                              $>ipclean
                              $db2fmcu -d...if not running then the following

from the main session...db2nkill -9...to kill all the db2 processes
again in duplicate session /home/db2dbas/das/bin/db2fm -i db2dbas -D
ps -ef | grep -i db2...to check any db2 process is running or not.

2) Installation of Fix pack

         Verify that you have atleast 700MB available on /usr/opt
            $df -m /opt
             Connect as root
             Go in DB2 FP repository and launch the following command
           $> cd <fix location>
           $> ./installFixPack -b /opt/IBM/db2/V9.5

Post Installation steps:

                 Update and restart of Instances
                 Update DB2 Instance as root
                            $cd /opt/IBM/db2/V9.5/instance
                            $./db2iupdt <instance name>
                 Update DB2 Admin Server db2as as root,
                            $./dasmigr
                            $./dasupdt <das id>
                 Stop and Start Admin Server
                            $db2admin stop
                            $db2admin start
                 Update each database as instance owner,
                            $db2updv95 –d <database Name>
                            $db2updv95 –d <database Name>
                 Verify db2level.

DB21085I Instance "db2inst1" uses "64" bits and DB2 code release "SQL09055" with level identifier "06060107".
Informational tokens are "DB2 v9.5.0.5", "s091123", "U829462", and Fix Pack "5".
Product is installed at "/opt/IBM/db2/V9.5".

                 Bind of DB2 UDB Databases:
                          Connect as instance administrator and launch the following commands
                                  $db2 terminate
                                  $db2 connect to <db name>
                                  $cd ~/sqllib/bnd
                                  $db2 BIND @db2ubind.lst BLOCKING ALL GRANT PUBLIC
                                  $db2 BIND @db2cli.lst BLOCKING ALL GRANT PUBLIC
                                  $db2 BIND db2schema.bnd BLOCKING ALL GRANT PUBLIC sqlerror continue
                                  $db2 connect reset
                                  $db2 terminate

                     $db2 BIND @applyur.lst isolation ur BLOCKING ALL GRANT PUBLIC
                     $db2 BIND @applycs.lst isolation cs BLOCKING ALL GRANT PUBLIC
                     $db2 BIND @capture.lst isolation ur BLOCKING ALL GRANT PUBLIC


Stop and Start the Instance
                 $db2stop
                 $db2start

Checking of Table spaces state:
                          $db2 list tablespaces on <database> | grep -i state
Test some commands after connecting to the database :
                          $db2 list tables for all
                          $db2 "select count (*) from schema.table/view"

$>>Enable the crontabs

ask the client to test and verify the applications

Back out plan:
             Downgrade DB2 Instance back to DB2 V9.5 fixpak3b as root,
             cd /opt/IBM/db2/V9/FP5/instance
            ./db2iupdt -D <instance name>
             Downgrade DB2 Admin Server
            ./dasupdt –D




Thursday 25 April 2013

Export

 The export utility extracts data from a table into a file.The command supports many different options.Let's start with a simple export command and discuss how to use the options to customize the command. The following example of the export command exports all the rows in the employee table to the file empdata.ixf in IXF format.

export to empdata.ixf of ixf select * from employee
All the keywords in this command are mandatory. that is, you have to provide theoutput file name , specify the file format, and the SELECT statement that will retrieve the rows to be exported. The exported file can be in a format of DEL, IXF, or WSF.

Using the optional messages clause you can specify a file name where warning and error messages of the export operation are logged.

The export command also supports SELECT statements with join. Thus, if you want to export data from two tables, they can be joined as shown example:



export to deptmgr.del of del messages deptmgr.out select deptno, deptname, firstnme, lastname, salary from employee, department where empno = mgrno

The above example joins the employee and department tables to obtain information for each department manager. If the command is successfully executed, the number of rows exported is returned :Number of rows exported: 8

SQL3104N The Export utility is beginning to export data to file "c:\deptmgr.del".

SQL3105N The Export utility has finished exporting "8" rows.

export to deptmgr.del of del modified by coldel; messages deptmgr.out select deptno, deptname, firstnme, lastname, salary from employee, department where empno = mgrno

export to deptmgr.del of del modified by coldel; chardel'' messages deptmgr.out select deptno, deptname, firstnme, lastname, salary from employee, department where empno = mgrno

export to deptmgr.del of del modified by coldel; chardel'' timestampformat="yyyy.mm.dd hh:mm" messages deptmgr.out select deptno, deptname, firstnme, lastname, salary from employee, department where empno = mgrno

export to mgrresume.del of del messages mgrresume.out lobs to c:\lobs lobfile resume modified by lobsinfine select deptno, deptname, firstnme, lastname, resume from employee a, emp_resume b where a.empno = b.empno

SELECT empno, firstnme, lastname, salary * 1.3 FROM employee WHERE workdept='A00'

 export to newsalary.ixf of ixf messages newsalary.out method n ('EMPLOYEENO', 'FIRSTNAME', 'LASTNAME', 'NEWSALARY') select empno, firstnme, lastname, salary * 1.3 from employee where workdept='A00'



DB2 data movement utilities



DB2 data movement utilities. The utilities provide a way to move data from one database to another. The source and target databases can be the same instance, in different instances on the same server, on different servers on the same platform, or on different platforms entirely.






To extract data from a table in a database, you use the export utility. The import and load utilities insert data from the input files into a specified table. db2move is a batch version of the data movement utilities; it can export, import, or load multiple tables with just one command.
Input/Output File Types:
  1.  Delimited ASCII (DEL)
  2.  Non-delimited ASCII (ASC)
  3.  PC version of Integrated Exchange Format (PC/IXF)
  4.  Worksheet format (WSF)
  5.  Cursor

Delimited ASCII (DEL) Format: this file format contains a stream of ASCII characters that are separated by row and column delimiters. Comma (,) is the default column delimiter and the carriage return is the default row delimiter. For character strings, DB2 uses double quotes ( " " ) as the string delimiter.
 
Non-delimited ASCII (ASC) : The ASC file format is also known as fixed length ASCII file format because each column length in the file has the same length as defined for the corresponding column definition in the table.

PC version of Integrated Exchange Format (PC/IXF) : PC/IXF (or simply IXF) files cannot be edited with a normal text editor. It uses the IXF data interchange architecture, which is a generic relational database exchange format that lets you move data among DB2 databases. PC/IXF can only be used for moving data between DB2 databases because it is an IBM proprietary format. In addition to data, the file also contains the data types and structure of the table. Therefore it can be used to first create the table in the target database and then import data.
 
Worksheet format (WSF) : WSF files are Lotus 1-2-3 and Symphony worksheets that the database manager supports. Any file names with these extensions are accepted: WKS, WK1, WRK, WR1, and WJ2. WSF files are mainly used for moving data between DB2 and these worksheets.
 
Cursor : The cursor format lets you load data into a table using a cursor. The cursor must be declared against an SQL query first before it can be referenced in the load command. You can only use the cursorfile format with the load utility.

Monday 22 April 2013

Troubleshooting db2 error " SQL0551N "

 


Error Message : SQL0551N "user does not have the privilege to perform operation GRANT"   
If you receive this message from the DB2 client while connecting to DB2 , you may have to bind the DB2 utility programs to the database. You must apply the procedure to each database you are using with the application server. Here is the binding procedure:
  1. Log in as your DB2 instance user (such as db2inst1), change to the bnd subdirectory of the instance, and start the DB2 utility.
      db2inst1@mymachine>  cd sqllib/bnd
      db2inst1@mymachine>  db2
    
  2. Connect to your database as the DB2 administrator:
      db2 => connect to mydatabase user db2admin using db2admin
    
    You will see the following info:
      Database Connection Information
      Database server        = DB2/NT 6.1.0
      SQL authorization ID   = DB2ADMIN
      Local database alias   = MYDATABASE
    
    1. Get the list of authorities for this authorization ID.  For example: SELECT * FROM TABLE (SYSPROC.AUTH_LIST_AUTHORITIES_FOR_AUTHID ('BOB', 'U'))AS T  ORDER BY AUTHORITY
    2. (Optional) Grant any missing authorities.  For example: GRANT DBADM ON DATABASE TO USER BOB
  3. Run the first bind command:
      db2 => bind @db2ubind.lst blocking all grant public
    
  4. Run the second bind command:
      db2 => bind @db2cli.lst blocking all grant public 
    

configure the DB2 client connection / Catalog the DB2 Database

   Windows NT    The application server connects using DB2 client aliases. These aliases are configured using IBM's Client Configuration Assistant. login must have administrator authority and the ID must be no longer than eight characters. You need to be the DB2 administrator or have administrator privileges to complete these steps.
 
 To create a new DB2 client alias:
 
  1. Open the DB2 Client Configuration Assistant from the DB2 for Windows NT program folder.
  2. Click the Add button at the top right of the Client Configuration Assistant screen. Select Next to continue.
  3. Choose to manually configure a connection to a DB2 database. Select Next to continue.
  4. Choose the appropriate protocol (default is TCP/IP). Select Next to continue.
  5. Choose the appropriate platform or LAN-based.
  6. Configure the DB2 server host name, TCP port number, and service name (optional) that your DB2 server is operating on. Select Next to continue.
  7. Enter the target database name. Select Next to continue.
  8. Enter the alias name (you will use this name later to add the database to the application server). Select Next to continue.
  9. (Optional) Register these settings as an ODBC data source. This step is not required but is recommended.
  10. Finally, test the connection from inside the Client Configuration Assistant.
 
 
Solaris   To establish a connection to your DB2 database, enter the DB2 command-line processor and enter the following two commands.
  catalog tcpip node <node name> remote <servername> server <portno>
where tcpipnodealias is the local alias for your DB2 server (usually the same as the servername), servername is the name of the DB2 server, and port# is the port on the database server that is set to receive TCP/IP calls.
  catalog database <dbname> as <aliasname> at node <node name> 
where databasename is the actual database name, aliasname is the local name of the database (which may be the same as the actual name), and tcpipnodealias is the name given in the first catalog statement.
To test the DB2 connection:
  connect to aliasname user <userid> using <password>


 

Friday 19 April 2013

DB2 System Commands


db2Command Line Utilities

>db2admin - DB2 Administration Server
            It is used to start and stop the administration server.
Step1: su dasusr1
Step2: cd /home/dasusr1/das/bin
Step3:./db2admin start

>db2cc – Starts the  Control Center.

>db2cmd - Open DB2 Command Window
                        Ex:       ]$ db2cmd

>db2fs - First Steps
Launches the First Steps GUI, which contains links to the functions users need to begin learning about and using DB2.
                        Ex:       ]$ db2fs

>db2eva -Event Analyzer
Starts the event analyzer, allowing the user to trace performance data produced by DB2 event monitors that have their data directed to files.
                        Ex:       ]$ db2eva

>db2evmon -    Event Monitor Productivity Tool
Formats event monitor file and named pipe output, and writes it to standard output.
Syntax: db2evmon –db <database-alias> evm <event-monitor-name> 'path-event-  
             monitor-target'
                        Ex:  ]$ db2evmon -db sample  -evm sample

>db2set - DB2 Profile Registry Command. Displays, sets, or removes DB2 profile
   variables. An External
environment registry command that supports local and remote administration, via the DB2          Administration Server, of DB2's environment variables stored in the DB2 profile registry.
                        Ex:       ]$db2set DB2AUTOSTART=YES

>db2ckmig - Database Pre-migration Tool
Verifies that a database can be migrated. For detailed information about using this tool, see one of the Quick Beginnings books.

                        Syntax:           db2ckmig sample -l  /home/db2inst1/mig.txt
                        Ex:                   ]$ db2ckmig sample -l  /home/itlokam/mig.txt
                                                db2ckmig was successful. Database(s) can be migrated.

>db2ckbkp - Check Backup
This utility allows the user to test the integrity of a backup image and determine whether or not it can be restored.
Ex :                  ]$ db2ckbkp -a SAMPLE.0.itlokam.NODE0000.CATN0000.20060728215319.001
                                    '
                                    '
                        Image Verification Complete – successful.
>db2ckrst -  It gives the restore command options of the backup timestamp
                      
Syntax: db2ckrst -d <database name> -t <timestamp>
                        Ex:       ]$ db2ckrst  -d sample -t 20060728215319
Suggested restore order of images using timestamp 20060728215319 for database sample.
================================= ========================
Suggested restore order of image using timestamp 20060728215319 for database sample.
================================= =========================

>db2rfpen - Reset rollforward pending state Command
Puts a database in rollforward pending state. If you are using high availability disaster recovery (HADR), the database is reset to a standard database.
                        Ex:       ]$ db2rfpen on sample

>db2logsforrfwd - List Logs Required for Rollforward Recovery Command
This utility allows a user to find out which log files are required for a table space rollforward operation.

Ex: bin]$ db2logsForRfwd            /home/itlokam/itlokam/NODE0000/SQL00001/DB2TSCHG.HIS
----------------------------------------------------------
Log file number       : S0000000.LOG
Tablespace ID         :
----------------------------------------------------------
Log file number       : S0000001.LOG
Tablespace ID         :
----------------------------------------------------------
Log file number       : S0000002.LOG
Tablespace ID         : 2 3
----------------------------------------------------------
Log file number       : S0000003.LOG
Tablespace ID         :
----------------------------------------------------------
Log file number       : S0000004.LOG
Tablespace ID         : 2
----------------------------------------------------------
Log file number       : S0000005.LOG
Tablespace ID         : 3
----------------------------------------------------------
Log file number       : S0000006.LOG
Tablespace ID         : 3
----------------------------------------------------------
Log file number       : S0000007.LOG
Tablespace ID         : 3
----------------------------------------------------------
Log file number       : S0000008.LOG
Tablespace ID         : 0 3
----------------------------------------------------------
Log file number       : S0000009.LOG

>db2batch - Benchmark Tool
It Reads SQL statements from either a flat file or standard input, dynamically prepares and describes the statements, and returns an answer set.
                        Syntax:                        db2batch  -d database name
                                                 -f  filename
                                                 -a username/password
                                                 -r output file
            Ex:       ]$ db2batch -d sample  -f / home/itlokam/sam.txt -r /home/itlokam/res.txt

            Bind is successful.  Used bindfile: /home/itlokam/sqllib/bnd/db2batch.bnd
            Running in Embedded Dynamic mode.

>db2bfd - Bind File Description Tool
Displays the contents of a bind file. This utility, which can be used to Examine and to verify the SQL statements within a bind file, as well as to display the precompile options used to create the bind file, may be helpful in problem determination related to an application's bind file.

            Ex:       ]$db2bfd -b /home/db2inst1/sqllib/bnd/db2am.bnd 

>db2level - Show DB2 Service Level Command
Shows the current Version and Service Level of the installed DB2 product. Output from this command goes to the console by default.

            Ex:       ]$ db2level
DB21085I  Instance "itlokam" uses "32" bits and DB2 code release "SQL08020" with level identifier "03010106".
Informational tokens are "DB2 v8.1.0.64", "s040812", "MI00086", and FixPak "7".
Product is installed at "/opt/IBM/db2/V8.1".

>db2relocatedb :It will rename the database
                Step1: Create a file with name relocate.cfg and add the following contents
                DB_NAME=TESTDB,PRODDB
                DB_PATH=/home/db2inst1
                INSTANCE=db2inst1
                NODENUM=0
                Step2: db2relocatedb /home/db2inst1/relocate.cfg

>db2cfExp - Connectivity Configuration Export Tool
Exports connectivity configuration information to an Export profile, which can later be imported at another DB2 Universal Database (UDB) workstation instance of similar instance                     type.
            Ex:       ]$ db2cfExp   /home/db2inst1/profile.txt

>db2cfimp - Connectivity Configuration Import Tool
Imports connectivity configuration information from a file known as a configuration profile.
This utility can be used to duplicate the connectivity information from another similar instance that was configured previously. It is especially useful on workstations that do not have the DB2CCA GUI tool installed, and in situations where multiple similar remote UDB clients are to be installed, configured, and maintained.
            Ex:       ]$ db2cfimp   /home/db2inst1/profile.txt

>db2tbst - Get Tablespace State. Accepts a hexadecimal table space state value, and
returns the state. The state value is part of the output from LIST ABLESPACES.
            Step1: Issue LIST TABLESPACES.
            Step2: Copy the STATE value in that.
            Step3: db2tbst 0x0000


>db2uiddl - Prepare Unique Index Conversion to V5 Semantics. Used to create DDL for
      all indexes into a flat file.
            Ex:       ]$ db2uiddl -d s >  /home/db2inst1/sam.txt

>db2trc - Trace
                  Controls the trace facility of a DB2 instance or the DB2 Administration Server.
Ex:       ]$ db2trc dmp db2trc.dmp

>db2icrt – Used to create Instance

            Step1: Create a user db2inst2 and add it to db2grp
            Step2: Switch to root
            Step3: cd  /opt/IBM/db2/V8.1/instance
            Step4: ./db2icrt -a server -u db2fenc1 db2inst2

>db2start - Start DB2.Starts the current database manager instance background
processes on a single database partition
EX:       ]$ db2start

>db2stop - Stop DB2.Stops the current database manager instance.
            EX:       ]$ db2stop

>db2idrop - Remove Instance

            Step1: Switch to root
            Step2: cd  /opt/IBM/db2/V8.1/instance
            Step3: ./db2idrop  db2inst2

>db2ilist - List Instances

            Step1: Switch to root
            Step2: cd  /opt/IBM/db2/V8.1/instance
            Step3: ./db2ilist

>db2imigr – To Migrate Instance from lower version to higher version

            Ex:     ]$ db2imigr  db2inst1  db2viper1

>db2iupdt - Update Instances

            Step1: Switch to root
            Step2: cd  /opt/IBM/db2/V8.1/instance
            Step3: ./db2iupdt db2inst1

>db2iset – It is used to set the registry variables for db2
instance]# ./db2iset
DB2NTNOCACHE=ON
DB2COMM=TCPIP
DB2AUTOSTART=YES
[root@ITLSYS64 instance]# ./db2iset DB2AUTOSTART=YES
[root@ITLSYS64 instance]# ./db2iset
DB2NTNOCACHE=ON
DB2COMM=TCPIP
DB2AUTOSTART=YES

>db2isetup - Creation of instance through GUI
Ex:       instance]# ./db2isetup

>db2advis - DB2 Index Advisor
                      Advises users on what indexes to create for one or more SQL statements.
                        syntax:                         db2advis -d dataname
  -w workload name
               -s statement
               -i filename
               -a userid
               -l disk limit
               -passwd password
               -t maxadvisetime
Ex:       ]$ db2advis -d sample -i /home/db2inst1/db2advis.in -t 5

                        Using user id as default schema name. Use -n option to specify schema
                        Explain tables not set up properly for schema ITLOKAM
                        The insert into the ADVISE_INSTANCE table has failed.

                        0 solutions were evaluated by the advisor
                        exiting with error code [-219]



db2audit - Audit Facility Administrator Tool
Step1: Configuring the audit facility.
            db2audit configure scope all status both
Step2: Starting the audit facility.
            db2audit start
Step3: Checking the log file
            cd /home/db2inst1/sqllib/security
            Open db2audit.log
            Check for the logs
Step4: Stopping the audit
            db2audit stop

>db2empfa - Enable Multi-page File Allocation
Enables the use of multi-page file allocation for a database. With multi-page file allocation enabled for SMS table spaces, disk space is allocated one Extent rather than one page at a time.
            Ex:       ]$ db2empfa sample

>db2ldcfg - Configure LDAP Environment. Configures the Lightweight Directory Access
      Protocol (LDAP) user distinguished name (DN) and password for the    
      current logon user in an LDAP environment using an IBM LDAP client.
                        Syntax: db2ldcfg -u <username> -w<password> -r
                        Ex:      

>db2licm - License Management Tool
Performs basic license functions in the absence of the Control Center. Adds, removes, lists, and modifies licenses and policies installed on the local system.
-a: Adds a license for a product. 
-e: Updates the enforcement policy on the system.  Valid values are: HARD and SOFT.
-p: Updates the license policy type to use on the system.  The keywords CONCURRENT, REGISTERED, or CONCURRENT REGISTERED can be specified.  Specify OFF to turn off all policies.
-r: Removes the license for a product. 
-u: Updates the number of user entitlements that have been purchased. 
-c: Updates the number of connector entitlements that have been purchased.
-n: Updates the number of entitled processors. 
-l: Lists all the products with available license information, including the product identifier.
-v: Displays version information.
 -? Displays help information. 

            Ex:       ]$ db2licm -a db2ese.lic
                                    db2licm –v : o/p 8.2

>db2sql92 - SQL92 Compliant SQL Statement Processor. Reads SQL statements from either a flat file or standard input, dynamically describes and prepares the statements, and returns an answer set. Supports concurrent connections to multiple databases.
Step1: Create a file with name statements.sql
Step2: Add the SQL statements
Select * from employee;
Step3: db2sql92 -d s -f /home/db2inst1/statements.sql -r /home/db2inst1/response.sql


>db2mtrk - Memory Tracker Command. It will give the memory details of db2 instance
      and database

            Ex:       ]$ db2mtrk -i -d -v -r 10
                        Tracking Memory on: 2006/07/28 at 23:41:38

Memory for instance
   Database Monitor Heap is of size 163840 bytes
   Other Memory is of size 1163264 bytes
   Total: 1327104 bytes

Memory for database: SAMPLE
   Backup/Restore/Util Heap is of size 16384 bytes
   Package Cache is of size 638976 bytes
   Catalog Cache Heap is of size 196608 bytes
   Buffer Pool Heap is of size 838631424 bytes
   Buffer Pool Heap is of size 655360 bytes
   Buffer Pool Heap is of size 393216 bytes
   Buffer Pool Heap is of size 262144 bytes
   Buffer Pool Heap is of size 196608 bytes
   Lock Manager Heap is of size 491520 bytes
   Database Heap is of size 3473408 bytes
   Other Memory is of size 0 bytes
   Total: 844955648 bytes
Tracking Memory on: 2006/07/28 at 23:41:48
>db2look - DB2 Statistics and DDL Extraction Tool
                     Extracts the required DDL (data definition language) statements to reproduce the database objects of a production database on a test database. db2look generates the DDL statements by object type
 -d: Database Name: This must be specified
 -e: Extract DDL file needed to duplicate database
 -xs: Export XSR objects and generate a script containing DDL statements
 -xdir: Path name: the directory in which XSR objects will be placed
 -u: Creator ID: If -u and -a are both not specified then $USER will be u sed
 -z: Schema name: If -z and -a are both specified then -z will be ignored
 -t: Generate statistics for the specified tables
 -tw: Generate DDLs for tables whose names match the pattern criteria (wil dcard characters) of the table name
 -h: More detailed help message
 -o: Redirects the output to the given file name
 -a: Generate statistics for all creators
 -m: Run the db2look utility in mimic mode
 -r: Do not generate RUNSTATS statements for mimic
 -l: Generate Database Layout: Database partition groups, Bufferpools and  Tablespaces
 -x: Generate Authorization statements DDL excluding the original definer  of the object
 -xd: Generate Authorization statements DDL including the original definer  of the object
 -f: Extract configuration parameters and environment variables
 -td: Specifies x to be statement delimiter (default is semicolon(;))
 -i: User ID to log on to the server where the database resides
 -w: Password to log on to the server where the database resides
 -noview: Do not generate CREATE VIEW ddl statements
 -wrapper: Generates DDLs for federated objects that apply to this wrapper
 -server: Generates DDLs for federated objects that apply to this server
 -nofed: Do not generate Federated DDL
 -fd: Generates db2fopt statements for opt_buffpage and opt_sortheap along  with other cfg and env parameters.
 -v: Generate DDL for view only, this option is ignored when -t is specif ied
 -dp: Generate DROP statement before CREATE statement
 -ct: Generate DDL Statements by object creation time

            Ex:       ]$db2look -d s -e  -o  /home/db2inst1/script.sql

>db2pd: As it’s a very important command line utility Refer to IBM site