728x90
 

Question

I found some indexes marked invalid after rollforward, or a HADR standby database become switched to primary.
Why the indexes are marked as invalid, and how I can recover the invalid indexes.

Cause

Db2 does not write index build or rebuild log records by default, rather Db2 marks the index as invalid so that recovery task can trigger to rebuild the index.

Answer

"Index rebuilding" means index creation, index reorg, classic table reorg, and rebuilding index in this article.
 
Indexes can be marked as invalid when:
  • Index rebuilding is not logged ( LOGINDEXBUILD=NO), then index rebuilding replayed.
  • Index rebuilding is logged ( LOGINDEXBUILD=YES), then index rebuilding replayed but INDEXREC is set as ACCESS_NO_REDO or RESTART_NO_REDO.
  • Failed offline reorg, or such failed offline reorg is replayed.
  • db2dart runs with /MI option.

Indexes can be rebuilt when:
  • There are one or more indexes marked invalid when a database restarts. i,e. Run RESTART DB with INDEXREC=RESTART
  • Someone access an index marked as invalid.
  • Run classic REORG TABLE command
  • Run REORG INDEXES or REORG INDEX command
  • Run CREATE INDEX statement
  • Run LOAD command, and it uses REBUILD option as INDEXING MODE
  • Run IMPORT or LOAD command with REPLACE option
  • Run TRAUNCATE TABLE statement

We can list all the indexes marked as invalid by the following query:
db2 "select tabschema, tabname, indname, datapartitionid, index_partitioning from table(sysproc.admin_get_index_info('','','')) as t where index_requires_rebuild='Y'"

We can recover the indexes marked as invalid by ether of the following ways.
 
a) Run RESTART DATABASE command (in case db cfg INDEXREC is set as RESTART)
The restart database command rebuild all the indexes set as INDEX_REQUIRES_REBUILD=Y
db2 restart database <database_name>
b) Run reorg indexes
db2 reorg indexes all on table <table_name> allow no access

Note: 
You can set LOGINDEXBUILD as YES to prevent indexes to be marked as invalid.
So, this setting is highly recommended in HADR databases.
Example:
db2 connect to <database_name>
db2 update db cfg using LOGINDEXBUILD YES

 

https://www.ibm.com/support/pages/db2-causes-mark-index-invalid-and-how-recover-indexes

 

[Db2] The causes to mark index invalid, and how to recover the indexes.

[Db2] The causes to mark index invalid, and how to recover the indexes.

www.ibm.com

 

728x90
728x90


Question

I want to prevent SQL0964C  "The transaction log for the database is full" error.
How can I monitor applications that remain uncommitted for a long time or consume huge amount of transaction log space?

 

Answer

The combination of MON_GET_UNIT_OF_WORK and MON_GET_CONNECTION table functions can be used to achieve such purpose.

  1. Create a file (mon_transactions.sql) containing following SQL:
    SELECT
    con.application_handle,
    con.application_id,
    con.application_name,
    con.client_pid,
    uow.uow_start_time,
    uow.uow_log_space_used
    FROM
    table(mon_get_connection(cast(null as bigint), -1)) as con,
    table(mon_get_unit_of_work(null, -1)) as uow
    WHERE
    con.application_handle = uow.application_handle and
    uow.uow_log_space_used != 0
    ORDER BY uow.uow_start_time ;
  2. Connect to the database that you want to monitor using user ID that has DBADM authority.
    db2 connect to [database]
  3. Execute the monitoring SQL created in Step 1. 
    db2 -tvf mon_transactions.sql

[example output]

APPLICATION_HANDLE  APPLICATION_ID                APPLICATION_NAME CLIENT_PID  UOW_START_TIME             UOW_LOG_SPACE_USED
------------------ ------------------------------ ---------------- ----------  -------------------------- ------------------
             20136 192.168.1.1.49538.181224175700 db2bp                 10648  2018-12-25-09.59.43.450650              15593
             20201 *LOCAL.db2inst1.181214145300   db2bp                  8948  2018-12-25-10.27.51.465542              15436
2 record(s) selected.

 

 

The application with a very old UOW_START_TIME could cause SQL0964C error. If the UOW_LOG_SPACE_USED keeps increasing for a particular application, that application may also cause a log full situation.

Additional tips

"mon_req_metrics" database configuration parameter needs to be set as BASE (default) or EXTENDED in order to collect the metrics using the monitoring SQL. You can confirm the current value of database configuration parameters with the following command.

db2 get db cfg for [database]

 

 

728x90
728x90

DB2 LUW 11버전이 출시되고, 업데이트가 이뤄지면서 이전과는 버전을 표기하는 방식이 바뀌었습니다.

아래 표와 링크에서 버전에서 나타내는 각 요소별 의미를 확인해보시기 바랍니다.

 

Element Example  Description
V - Version Number11.1.2.3
  • Indicates a separate IBM licensed program that usually has significant new code or capability
  • Contains major feature changes
  • Starts a new 5 year maintenance clock
  • Downloads found on Passport Advantage
R - Release Number11.1.2.3
  • Minor but significant feature change release
  • Starts a new 5 year maintenance clock
  • Downloads found on Passport Advantage
M - Modification Number11.1.2.3
  • Product refresh also referred to as a Mod Pack
  • Can include new functionality
  • Does not start a new maintenance clock
  • Downloads found on Fix Central
F - Fix Number11.1.2.3
  • Cumulative update of all available fixes and APARs
  • Does not start a new maintenance clock
  • Downloads found on Fix Central
iFix - Interim Fix11.1.2.3 iFix001
  • Tested and verified set of small number of key fixes and APARs, available to all
  • Subsequent iFixes are cumulative
  • Downloads found on Fix Central
  • Supported for the maintenance life of the Version.Release

 

출처 : https://www.ibm.com/developerworks/community/blogs/IMSupport/entry/All_about_ifixes_interim_fixes?lang=en

728x90
728x90

Question

When a DB2 java application is executing a lot of concurrent SQL statements, it may hit the limit reporting "Out of Package Error Occurred" with the SQLCODE -805. If you encounter this error, You may ask what the limit is for the number of concurrent statements for a DB2 Java application and how to increase it.

Answer

When a DB2 Java application is running a dynamic SQL statement, it uses a dynamic section from DB2 CLI packages at DB2 server side to prepare/execute the statement. Please note that these DB2 CLI packages are exactly the same packages used by a CLI application.
By default, there are 3 large CLI packages (containing 385 sections) and 3 small CLI packages (containing 65 sections) bound at a DB2 database server. There are two sections from each package (both large and small) which are reserved for positioned update/delete statements and execute immediate statements. Therefore the total number of available sections for all other statements by default is (3 * 63) + (3 * 383) = 1338, which means by default a DB2 Java application can only run 1338 dynamic statements at one time.

When this limit is hit, the application will receive an error of "Out of Package Error Occurred" with SQLCODE -805, which means the DB2 server was running out of dynamic sections available from the CLI packages.

For example, running below Java application would hit the limit and report the error as below:


PreparedStatement pStmt = null;
for (int i=1; i<=1339; i++) {
pStmt = db.con.prepareStatement("insert into myt values (1, 'name1')");
pStmt.execute();
}


***** Out of Package Error Occurred (2014-05-14 22:20:32.431) *****

Exception stack trace:
com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-805, SQLSTATE=51002, SQLERRMC=NULLID.SYSLH204 0X5359534C564C3031, DRIVER=3.64.106
com.ibm.db2.jcc.am.bd.a(bd.java:682)
com.ibm.db2.jcc.am.bd.a(bd.java:60)
com.ibm.db2.jcc.am.bd.a(bd.java:127)
com.ibm.db2.jcc.am.io.c(io.java:2706)
com.ibm.db2.jcc.t4.ab.p(ab.java:872)
com.ibm.db2.jcc.t4.ab.h(ab.java:144)
com.ibm.db2.jcc.t4.ab.b(ab.java:41)
com.ibm.db2.jcc.t4.p.a(p.java:32)
com.ibm.db2.jcc.t4.qb.i(qb.java:135)
com.ibm.db2.jcc.am.io.gb(io.java:2112)
com.ibm.db2.jcc.am.jo.rc(jo.java:3526)
com.ibm.db2.jcc.am.jo.b(jo.java:3976)
com.ibm.db2.jcc.am.jo.hc(jo.java:2732)
com.ibm.db2.jcc.am.jo.execute(jo.java:2715)
DbConn2.main(DbConn2.java:74)

Concurrently open statements:
1. SQL string: INSERT INTO MYT VALUES (1, 'NAME1')
Number of statements: 1339
********************

DB2 SQL Error: SQLCODE=-805, SQLSTATE=51002, SQLERRMC=NULLID.SYSLH204 0X5359534C564C3031, DRIVER=3.64.106


Then what to do if you encounter above errors?

1) firstly you need to check if you can modify the application to avoid running so many dynamic SQL statements at the same time. 

2) If you can't avoid it, you will need to increase the number of available sections by increasing the number of DB2 CLI packages. 

Please note that only the number of DB2 CLI large packages can be increased, not for small packages, and the maximum number of large packages you can increase to is 30, which also basically means the maximum available sections would be (3 * 63) + (30 * 383) = 11679.

3) To increase the number of large CLI packages, you can run DB2 bind command with CLIPKG option via the instance owner as following example:

cd ~/sqllib/bnd
db2 connect to SAMPLE

--CLPKG 10, means it will increase the number of large CLI packages to 10.
db2 "bind @db2cli.lst CLIPKG 10 grant public blocking all"

--You can then check the number of CLI large packages per isolation and cursor holdability, where you will see the number would be 10 now.

db2 "list packages for all"

db2 terminate


http://www-01.ibm.com/support/docview.wss?uid=swg21670200&myns=swgimgmt&mynp=OCSSEPGG&mync=E

728x90
728x90

Question

How to collect explain data / access plan for SQL stored procedures in DB2?

Answer

In both techniques outlined below, the explain tables need to be created. For more information on doing this task, see Explain Tables.

Technique 1: Obtain the explain plan when creating the stored procedure:

1) Turn on explain either:

  • Dynamically within the scope of the current session by issuing
    db2 "call SET_ROUTINE_OPTS('EXPLAIN ALL')" 
  • Or, globally at the instance level if the procedure is not being called within the current session
    db2set DB2_SQLROUTINE_PREPOPTS="EXPLAIN ALL"
    db2 terminate 
    db2stop 
    db2start 
2) Run the create statement for the SQL procedure that requires explaining. If one of the same name already exists, you may need to drop the procedure first or create a similar procedure under a different schema or name. 

3) The resulting explain data will be stored in the explain tables and can be extracted with a command such as the following: 
db2exfmt -d db_name -g TIC -w -1 -n % -s % -# 0 -o outputfilename

4) Disable explain by either issuing either one of these commands depending on how it was enabled. 
  • If it was turned on for the current session: 
    db2 "CALL SYSPROC.SET_ROUTINE_OPTS('')"
  • If it was turned on globally
    db2set DB2_SQLROUTINE_PREPOPTS=
    db2 terminate 
    db2stop 
    db2start

Technique 2: Obtain the explain plan from the package without needing to re-create the procedure: 

Assuming the explain tables under a schema called EXPLAIN_SCHEMA, do the following: 

1) Call the stored procedure 

2) Using a unique portion of the SQL statement from the body of the stored procedure logic you are interested in obtaining the explain for, use the following SQL statement to obtain the executable_id. This is an example if the SQL statement contains "INSERT INTO SYSIBM.SYSDUMMY1". Note: The query is case-sensitive.

db2 "SELECT executable_id FROM TABLE(MON_GET_PKG_CACHE_STMT (NULL, NULL,NULL, -1)) AS T where stmt_text like '%INSERT INTO SYSIBM.SYSDUMMY1%'"

3) With the executable_id returned in step 2 (For example: x'0100000000000000581E00000000000002000000010020140109134503816499'), make the following call. Also replace EXPLAIN_SCHEMA with your actual explain schema.

db2 "call EXPLAIN_FROM_SECTION(x'0100000000000000581E00000000000002000000010020140109134503816499', 'M', NULL, 0, 'EXPLAIN_SCHEMA', ?, ?, ?, ?, ?)"

This will populate the explain tables under the schema you specified

4) Run this command to extract the explain plan:
db2exfmt -d <db name> -g TIC -w -1 -n % -s % -# 0 -o exfmt.out



http://www-01.ibm.com/support/docview.wss?uid=swg21279292

728x90
728x90

Question

How to move DB2 instance and databases from one filesystem to another

Cause

This is just to show all the overall steps needed to move the instance and databases. This is one of the ways.

Answer

First, need to take a full off-line db2 backup of the databases.

Then preserve all the instance level and database level configurations.

Specially, the dbm config, database config, registry settings.

db2cfexp could be used to preserve the instance level configurations,

http://www-01.ibm.com/support/knowledgecenter/api/content/SSEPGG_9.7.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0002442.html

Then, drop the database and instance from current location.

Recreate instance in new location.

Update all the configurations as preserved earlier.

db2cfimp could be used to import back the instance level configurations,
http://www-01.ibm.com/support/knowledgecenter/api/content/SSEPGG_9.7.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0002441.html

Then perform a redirect restore of the databases under new instance if the new container paths needs to be defined. Though the underline filesystem is changed, if the exact same paths as the source location are present in the destination location then regular restore should work fine.

Just to reiterate that the database level configurations will be propagated as part of backup/restore process and need not have to be taken care separately unless some new paths have to be redefined in the destination locations, example active log directory, archive path etc.


http://www-01.ibm.com/support/docview.wss?uid=swg21572030&myns=swgimgmt&mynp=OCSSEPGG&mync=E

728x90
728x90

아래 내용은 DB2 10.5 환경의 UTF-8 코드셋 데이터베이스를 기준으로 합니다.

(eucKR 코드셋에서도 비슷하게 작동할 것으로 보입니다만 테스트가 필요합니다)

DB2에서 멀티바이트 문자에 LENGTH 함수를 사용하면 바이트 값을 리턴합니다.


UTF-8 인코딩에서 한글은 일반적으로 3바이트로 표현됩니다. (가 : ea b0 80)

DB2의 LENGTH 함수에서는 3을 리턴합니다.


10.5버전부터 LENGTH2, LENGTH4 와 같은 스칼라 함수를 지원합니다.


$ db2 "values length('가')"


1

-----------

          3


  1 record(s) selected.


$ db2 "values length2('가')"


1

-----------

          1


  1 record(s) selected.


$ db2 "values length4('가')"


1

-----------

          1


위와 같이 DB2의 LENGTH 함수 실행결과에서는 순수하게 바이트 길이를 표시해주고 length2 와 length4는 멀티바이트에 대응한 글자길이를 보여주게 됩니다.10.5 이전 버전에서는 character_length (또는 length) 함수에서 codeunits16, codeunits32 와 같은 인자값을 지정하여 사용했습니다. 유니코드의 경우 보통 3바이트로 표현하나 4바이트로 표현하는 문자도 아주 간혹 있어서 이같은 경우에는 codeunit32를 사용할 필요도 있습니다. 그러나 한글의 경우에는 4바이트로 표현하는 예는 없는 것 같습니다. 이에 대해 아시는 바가 있다면 알려주시기를 부탁드립니다.


참조. 오라클 작동방식 (11.2 버전 기준)

오라클의 경우 LENGTH 함수 실행결과 글자길이값을 보여줍니다. 오라클에서도 LENGTH2, LENGTH4 함수가 있는데 역시 DB2와 동일하게 작동합니다. 원래는 ORACLE함수이나 DB2에서도 호환성 측면에서 추가된 것으로 보입니다. 유니코드 캐릭터셋의 DB에서는 LENGTH4 함수가 LENGTH와 동일한 결과값을 보여줍니다. (기타 캐릭터셋에서는 확인이 필요합니다)


# export LANG=KO_KR.UTF-8

# export NLS_LANG=NLS_LANG=AMERICAN_AMERICA.AL32UTF8

# sqlplus scott/tiger


SQL> create table utftest (a varchar(100));


Table created.


SQL> insert into utftest values ('한?글');


1 row created.


SQL> select * from utftest;


A

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

한?글


SQL> select length(a) from utftest;


 LENGTH(A)

----------

         3


SQL> select length2(a) from utftest;


LENGTH2(A)

----------

         4


SQL>  select length4(a) from utftest;


LENGTH4(A)

----------

         3


SQL> insert into utftest values ('a한?글b');


1 row created.


SQL> select * from utftest;


A

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

한?글

a한?글b


SQL> select length(a) from utftest;


 LENGTH(A)

----------

         3

         5


SQL> select length2(a) from utftest;


LENGTH2(A)

----------

         4

         6


SQL> select length4(a) from utftest;


LENGTH4(A)

----------

         3

         5



참조

http://www.utf8-chartable.de/unicode-utf8-table.pl

http://www.ibm.com/developerworks/data/library/techarticle/dm-0705nair/

728x90
728x90


Problem(Abstract)

You have multiple tables in your database that have changed extensively and you are experiencing a performance degradation. Reorg and runstats are recommended on these tables. You can create reorg and runstats scripts to make DB2® performance tuning easy.

Resolving the problem

To generate and run reorg and runstats scripts:

  1. Log in as the DB2 administrator, and connect to the database.

  2. To create a script for reorg table, run the following command on one line:
    db2 "list tables for all" | awk '{print $2"." $1}' | awk '/\w/ {print $0}' | sed '/^Schema.Table/d' | sed '/^record(s)./d' | sed 's/^/REORG TABLE /g' | sed 's/$/;/g' > /tmp/reorg_tbl.ddl

  3. To create a script for reorg index, run the following command on one line:
    db2 "list tables for all" | awk '{print $2"." $1}' | awk '/\w/ {print $0}' | sed '/^Schema.Table/d' | sed '/^record(s)./d' | sed 's/^/REORG INDEXES ALL FOR TABLE /g' | sed 's/$/;/g' > /tmp/reorg_idx.ddl

  4. To create a script for runstats, run the following command on one line:
    db2 "list tables for all" | awk '{print $2"." $1}' | awk '/\w/ {print $0}' | sed '/^Schema.Table/d' | sed '/^record(s)./d' | sed 's/^/RUNSTATS on TABLE /g' | sed 's/$/ WITH DISTRIBUTION AND DETAILED INDEXES ALL;/g' > /tmp/runstats_tbl.ddl

  5. Run reorg against tables and indexes, then runstats by entering the following lines:
    db2 -tvf /tmp/reorg_tbl.ddl
    db2 -tvf /tmp/reorg_idx.ddl
    db2 -tvf /tmp/runstats_tbl.ddl

  6. Ignore the following message if you receive it: 
    SQL2212N The specified table is a view. The Reorganize Table utility cannot be run against a view.

  7. To capture the message printed on screen, you can pipe the standard output into a file, such as with the following command:
    db2 -tvf /tmp/runstats_tbl.ddl > filename.log 2>&1

    NOTE: The commands in step 2, 3 and 4 will not run on windows system.


The following method can also be used to reorg all the tables in a database on Linux, Unix and Windows. 
  1. Log in as the DB2 administrator, and connect to the database.
  2. To create a script for reorg table, run the following command on one line:

    db2 -x "select 'REORG TABLE ' ||rtrim (tabschema)|| '.' || rtrim (tabname) || ' ;' from syscat.tables where tabschema not like 'SYS%' and type = 'T'" > reorg.out
  3. Run reorg against tables entering the following line:
    db2 -tvf reorg.out
    NOTE: The where clause in step 2 can be altered to include other tables in the reorg.out script. 
    It is recommended to runstats on any table that has been reorged. 
    Also, these commands may not work on all versions and levels of Unix and Linux.


http://www-01.ibm.com/support/docview.wss?uid=swg21444174&myns=swgimgmt&mynp=OCSSEPGG&mync=E

728x90
728x90


Question

Is it possible to prevent incoming database-connection attempts from application layer/driver from automatically activating the database.

Cause

Often, during maintenance events, a database is deactivated and the database-instance is stopped but the application is not stopped and will continue to attempt to establish a connection to the database while the database is under maintenance, this is not a problem in itself.
Later after maintenance completes and the database-instance is restarted and the database is activated, the application's attempt to establish a database connection will be successful.

However, there is a timing window where, after maintenance completes and the database-instance is started but before the database is activated, an application's database connection attempt can come in and automatically start database activation before a DBA has explicitly activated it. Since database activation can sometimes take several minutes, the application might timeout before the activation completes, and rollback the database activation. If the number of application threads attempting to connect to the database is very large, they may repeatedly start database activation ahead of the DBA's request to explicitly activate the database, and repeatedly timeout and rollback the activation. 
This can cause a repeated loop of automatic database activation and timeout/rollback, while the DBA's explicit request to activate the database appears to hang.

Answer

In order to prevent this kind of phenomenon, we can temporarily pause application database connection attempts from reaching the database server and automatically starting database activation, so that the DBA's request to explicitly activate the database can complete.


There are two methods that can be used:

Method #1: use the db2trc -suspend option to pause incoming database connections from reaching the database server, and then un-pause them after the DBA has completed database activation. (note that this method does not actually perform a trace, so it does not have any performance impact).

1) db2trc on -debug DB2.SQLCC.sqlcctcpconnmgr_child.115 -suspend 
2) db2start 
3) db2 activate database <dbname>
4) db2trc off 


Method #2: use the 'db2start admin mode restricted access' command to quiesce the database in restricted mode during db2start, and then unquiesce after the database activation is complete.

1) db2start admin mode restricted access 
2) db2 activate database <dbname>
3) db2 unquiesce instance <instance name>


http://www-01.ibm.com/support/docview.wss?uid=swg21673436&myns=swgimgmt&mynp=OCSSEPGG&mync=E

728x90
728x90


Question

This document describes how to determine if a table has been manually taken out of check pending state.

Answer

To determine if a table has been taken out of check pending (by the SET INTEGRITY ... IMMEDIATE UNCHECKED command), you can use the following SELECT query to see what options were used to perform the SET INTEGRITY command: 

select tabschema as Schema, tabname as Name, status as State, substr(const_checked,1,1) as Foreign_Keys, substr(const_checked,2,1) as Check_Constraints, substr(const_checked,5,1) as Summary_Tables from syscat.tables where tabname = '<tablename>' and tabschema = '<schema>'


...where <tablename> is the table and <schema> is the table schema.

For example, if <schema> = db2inst1 and <tablename> = employee, then an example of the result of the query is as follows:


SCHEMA NAME STATE FOREIGN_KEYS CHECK_CONSTRAINTS SUMMARY_TABLES
-------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------- ----- ------------ ----------------- --------------
DB2INST1 EMPLOYEE N U Y Y 

1 record(s) selected.

The FOREIGN_KEYS column shows the status of the check constraint for table DB2INST1.EMPLOYEE and is shown to have a value of 'U' -- indicating it was checked by the user using the SET INTEGRITY ... IMMEDIATE UNCHECKED command.


728x90

+ Recent posts