DB2入门操作之二

查看db2版本
db2 => select * from sysibm.sysversions
列出所有实例
[db2inst1@xifenfei ~]$ db2ilist
db2inst1
列出当前实例
[db2inst1@xifenfei ~]$ db2 get instance
 The current database manager instance is:  db2inst1
察看示例配置文件
[db2inst1@xifenfei ~]$ db2 get dbm cfg|more
察看数据库配置参数信息
[db2inst1@xifenfei ~]$ db2 get db cfg for TOOLSDB|more
列出所有表空间的详细信息
[db2inst1@xifenfei ~]$ db2 list tablespaces show detail|more
连接数据库
[db2inst1@xifenfei ~]$ db2 connect to TOOLSDB
   Database Connection Information
 Database server        = DB2/LINUX 9.7.4
 SQL authorization ID   = DB2INST1
 Local database alias   = TOOLSDB
sql操作数据库
[db2inst1@xifenfei ~]$ db2 "select * from t_xff"
查看端口号
[db2inst1@xifenfei ~]$ db2 get dbm cfg|grep SVCENAME
查看表结构
[db2inst1@xifenfei ~]$ db2 describe table t_xifenfei
查看某个表索引
[db2inst1@xifenfei ~]$ db2 describe indexes for table t_xff
显示当前活动数据库
[db2inst1@xifenfei ~]$ db2 list active databases
列出所有的系统表
[db2inst1@xifenfei ~]$ db2 list tables for system
列出表空间
[db2inst1@xifenfei ~]$ db2 list tablespaces
显示用户数据库的存取权限
[db2inst1@xifenfei ~]$ db2 GET AUTHORIZATIONS
检查 DB2 数据库管理程序配置
[db2inst1@xifenfei ~]$ db2 get dbm cfg

通过hash_value获取sql语句执行计划

当我们没有权限访问业务表,但是需要查看shared pool中部分sql语句的执行计划,原则上来说,查询v$sql_plan视图结合hash_value可以实现,但是因为这个是表格形式,看起来不太美观,和我们长看的执行计划有一定的出入,这里提供两个脚本,实现查看该种情况下的执行计划。
oracle 9i

[oracle@xifenfei ~]$ more get_plan.sql
set pagesize 0
set linesize 150
set serveroutput on size 10000
col plan_table_output format a125
undefine hash_value
set verify off feedback off
var hash_value varchar2(20)
begin
  :hash_value := '&hash_value';
end;
/
insert into plan_table
      (statement_id,timestamp,operation,options,object_node,object_owner,object_name,
       optimizer,search_columns,id,parent_id,position,cost,cardinality,bytes,other_tag,
       partition_start,partition_stop,partition_id,other,distribution,
       cpu_cost,io_cost,temp_space,access_predicates,filter_predicates
      )
select distinct hash_value,sysdate,operation,options,object_node,object_owner,object_name,
       optimizer,search_columns,id,parent_id,position,cost,cardinality,bytes,other_tag,
       partition_start,partition_stop,partition_id,other,distribution,
       cpu_cost,io_cost,temp_space,access_predicates,filter_predicates
  from v$sql_plan
 where hash_value = :hash_value
/
col piece noprint
select distinct piece,sql_text from v$sqltext where hash_value = :hash_value order by piece
/
@?/rdbms/admin/utlxplp.sql
set linesize 80
set verify on feedback on pagesize 1000

oracle 10g/11g

[oracle@xifenfei ~]$ more get_plan.sql
set pagesize 0
set linesize 150
set serveroutput on size 10000
col plan_table_output format a125
undefine hash_value
set verify off feedback off
var hash_value varchar2(20)
begin
  :hash_value := '&hash_value';
end;
/
insert into plan_table
      (statement_id,timestamp,operation,options,object_node,object_owner,object_name,
       optimizer,search_columns,id,parent_id,position,cost,cardinality,bytes,other_tag,
       partition_start,partition_stop,partition_id,other,distribution,
       cpu_cost,io_cost,temp_space,access_predicates,filter_predicates,
       plan_id,OBJECT_ALIAS,DEPTH,PROJECTION,TIME,QBLOCK_NAME
      )
select distinct hash_value,sysdate,operation,options,object_node,object_owner,object_name,
       optimizer,search_columns,id,parent_id,position,cost,cardinality,bytes,other_tag,
       partition_start,partition_stop,partition_id,other,distribution,
       cpu_cost,io_cost,temp_space,access_predicates,filter_predicates,
       :hash_value,OBJECT_ALIAS,DEPTH,PROJECTION,TIME,QBLOCK_NAME
  from v$sql_plan
 where hash_value = :hash_value
/
col piece noprint
select distinct piece,sql_text from v$sqltext where hash_value = :hash_value order by piece
/
@?/rdbms/admin/utlxplp.sql
set linesize 80
set verify on feedback on pagesize 1000

使用方法

SQL> SELECT hash_value FROM V$SQL WHERE SQL_TEXT
  2  LIKE 'SELECT * FROM SYS.SMON_SCN_TIME';
HASH_VALUE
----------
3019898357
SQL> @get_plan.sql
Enter value for hash_value: 3019898357
SELECT * FROM SYS.SMON_SCN_TIME
-----------------------------------------------------------------------------------
| Id  | Operation         | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |               |       |       |     3 (100)|          |
|   1 |  TABLE ACCESS FULL| SMON_SCN_TIME |     1 |  1163 |     3   (0)| 00:00:01 |
-----------------------------------------------------------------------------------

补充说明
其实9i和10g/11g中得出执行计划的出入就是在plan_table表上
在9i中:plan_table表需要通过脚本创建并且授权

SQL> connect / as sysdba;
SQL> @?/rdbms/admin/utlxplan.sql;
SQL> create public synonym plan_table for plan_table; --建立同义词
SQL> grant all on plan_table to public;--授权所有用户

在10g/11g中:plan_table表系统自带,不需要创建。因为plan_table表中含有plan_id列,而得出执行计划时该列不能为空,所以上面脚本中对于10/11g数据库必须要填充plan_id值

通过修改基表(link$)让非public dblink变为public

有些朋友创建了一个非public的dblink,现在该数据库的其他用户需要去使用该dblink,在正常情况下无访问权限,需要重新建一个dblink,或者将原dblink修改为public。但是由于忘记了原dblink的目标段的密码,使得创建或者修改dblink的步骤无法进行下去。这里通过修改基表(link$),解决该问题。

创建dblink

SQL> show user;
USER is "SYS"
SQL> create database link "xff_dblink"
  2  connect to TEST
  3  identified by "test"
  4  using '11.1.1.1:1521/mcrm';
Database link created.
SQL> select * from dba_db_links where db_link like 'XFF_DBLINK%';
OWNER DB_LINK                                     USERN HOST               CREATED
----- ------------------------------------------- ----- ------------------ --------
SYS   XFF_DBLINK.REGRESS.RDBMS.DEV.US.ORACLE.COM  TEST  11.1.1.1:1521/mcrm 29-MAR-12
SQL> select sysdate from dual@xff_dblink;
SYSDATE
---------
29-MAR-12
SQL> CONN TEST/TEST
Connected.
SQL> SELECT SYSDATE FROM DUAL@XFF_DBLINK;
SELECT SYSDATE FROM DUAL@XFF_DBLINK
                         *
ERROR at line 1:
ORA-02019: connection description for remote database not found
--该dblink不是public的,所以test用户无权访问

dblink变为public类型

SQL> CONN / AS SYSDBA
Connected.
SQL> set long 1000
SQL> select  text from dba_views where view_name='DBA_DB_LINKS';
TEXT
-------------------------------------------------------------------
select u.name, l.name, l.userid, l.host, l.ctime
from sys.link$ l, sys.user$ u
where l.owner# = u.user#
--查询出dblink相关的基表有link$和user$
SQL> desc sys.link$
 Name                          Null?    Type
 ----------------------------- -------- --------------------
 OWNER#                        NOT NULL NUMBER
 NAME                          NOT NULL VARCHAR2(128)
 CTIME                         NOT NULL DATE
 HOST                                   VARCHAR2(2000)
 USERID                                 VARCHAR2(30)
 PASSWORD                               VARCHAR2(30)
 FLAG                                   NUMBER
 AUTHUSR                                VARCHAR2(30)
 AUTHPWD                                VARCHAR2(30)
 PASSWORDX                              RAW(128)
 AUTHPWDX                               RAW(128)
SQL> select owner# from sys.link$ where name like 'XFF_DBLINK%';
    OWNER#
----------
         0
--XFF_DBLINK对应的用户标识记录在link$.owner#中
SQL> SELECT USER#,NAME FROM USER$ WHERE name in ('SYS','PUBLIC');
     USER# NAME
---------- ------------------------------
         1 PUBLIC
         0 SYS
--现link$.owner#值为0,表示该dblink所属用户为SYS,现在让该dblink变为public
--现需要让该dblink变为public,需要做的是修改link$.owner#的值为1
SQL> UPDATE LINK$ SET OWNER#=1 WHERE name like 'XFF_DBLINK%';
1 row updated.
SQL> COMMIT;
Commit complete.
--需要刷新shared_pool
SQL> ALTER SYSTEM FLUSH SHARED_POOL;
System altered.
--查看dblink所属者,已经修改为public
SQL> select owner from dba_db_links where db_link like 'XFF_DBLINK%';
OWNER
----------
PUBLIC
--测试dblink是否成功
SQL> CONN TEST/TEST
Connected.
SQL> SELECT SYSDATE FROM DUAL@XFF_DBLINK;
SYSDATE
---------
29-MAR-12

ORA-27103 when Memory target parameter is set to more than 3 GB(11.1.0.7)

朋友在数据库软件从11.1.0.6升级到11.1.0.7后,发现数据库无法打开,不能继续下一步升级
数据库启动

SQL> startup upgrade
ORA-03113: end-of-file on communication channel

alert日志

Starting ORACLE instance (normal)
LICENSE_MAX_SESSION = 0
LICENSE_SESSIONS_WARNING = 0
Picked latch-free SCN scheme 3
Using LOG_ARCHIVE_DEST_10 parameter default value as USE_DB_RECOVERY_FILE_DEST
Autotune of undo retention is turned on.
IMODE=BR
ILAT =182
LICENSE_MAX_USERS = 0
SYS auditing is disabled
Starting up ORACLE RDBMS Version: 11.1.0.7.0.
Using parameter settings in server-side spfile /u01/app/oracle/product/11.1.0/db_1/dbs/spfilecenterdb.ora
System parameters with non-default values:
  processes                = 1500
  sessions                 = 1655
  memory_target            = 12864M
  control_files            = "/u01/app/oracle/oradata/centerdb/control01.ctl"
  control_files            = "/u01/app/oracle/oradata/centerdb/control02.ctl"
  control_files            = "/u01/app/oracle/oradata/centerdb/control03.ctl"
  db_block_size            = 8192
  compatible               = "11.1.0.0.0"
  db_recovery_file_dest    = "/u01/app/oracle/flash_recovery_area"
  db_recovery_file_dest_size= 2G
  undo_tablespace          = "UNDOTBS1"
  remote_login_passwordfile= "EXCLUSIVE"
  db_domain                = ""
  dispatchers              = "(PROTOCOL=TCP) (SERVICE=centerdbXDB)"
  audit_file_dest          = "/u01/app/oracle/admin/centerdb/adump"
  audit_trail              = "DB"
  db_name                  = "centerdb"
  open_cursors             = 300
  diagnostic_dest          = "/u01/app/oracle"
Thu Mar 29 15:47:06 2012
PMON started with pid=2, OS id=16324
Thu Mar 29 15:47:06 2012
VKTM started with pid=3, OS id=16326 at elevated priority
VKTM running at (20)ms precision
Thu Mar 29 15:47:06 2012
DIAG started with pid=4, OS id=16330
Thu Mar 29 15:47:06 2012
DBRM started with pid=5, OS id=16332
Thu Mar 29 15:47:06 2012
PSP0 started with pid=6, OS id=16334
Thu Mar 29 15:47:06 2012
DIA0 started with pid=7, OS id=16336
Thu Mar 29 15:47:06 2012
MMAN started with pid=8, OS id=16338
Thu Mar 29 15:47:06 2012
DBW0 started with pid=9, OS id=16340
Thu Mar 29 15:47:06 2012
DBW1 started with pid=10, OS id=16342
Thu Mar 29 15:47:06 2012
DBW2 started with pid=11, OS id=16344
Thu Mar 29 15:47:06 2012
DBW3 started with pid=12, OS id=16346
Thu Mar 29 15:47:06 2012
DBW4 started with pid=13, OS id=16348
Thu Mar 29 15:47:06 2012
DBW5 started with pid=14, OS id=16350
Thu Mar 29 15:47:06 2012
LGWR started with pid=15, OS id=16352
Thu Mar 29 15:47:06 2012
CKPT started with pid=16, OS id=16354
Thu Mar 29 15:47:06 2012
SMON started with pid=17, OS id=16356
Thu Mar 29 15:47:06 2012
RECO started with pid=18, OS id=16358
Thu Mar 29 15:47:06 2012
MMON started with pid=19, OS id=16360
starting up 1 dispatcher(s) for network address '(ADDRESS=(PARTIAL=YES)(PROTOCOL=TCP))'...
Thu Mar 29 15:47:06 2012
MMNL started with pid=20, OS id=16362
starting up 1 shared server(s) ...
Errors in file /u01/app/oracle/diag/rdbms/centerdb/centerdb/trace/centerdb_mman_16338.trc:
ORA-27103: internal error
Additional information: -1
Additional information: 1
MMAN (ospid: 16338): terminating the instance due to error 27103
Instance terminated by MMAN, pid = 16338

这里可以发现memory_target在12g以上

trace文件内容

[oracle@fcdb trace]$ more /u01/app/oracle/diag/rdbms/centerdb/centerdb/trace/centerdb_mman_16338.trc
Trace file /u01/app/oracle/diag/rdbms/centerdb/centerdb/trace/centerdb_mman_16338.trc
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
ORACLE_HOME = /u01/app/oracle/product/11.1.0/db_1
System name:    Linux
Node name:      fcdb
Release:        2.6.18-164.el5
Version:        #1 SMP Tue Aug 18 15:51:48 EDT 2009
Machine:        x86_64
Instance name: centerdb
Redo thread mounted by this instance: 0 <none>
Oracle process number: 8
Unix process pid: 16338, image: oracle@fcdb (MMAN)
*** 2012-03-29 15:47:06.865
*** SESSION ID:(1648.1) 2012-03-29 15:47:06.865
*** CLIENT ID:() 2012-03-29 15:47:06.865
*** SERVICE NAME:() 2012-03-29 15:47:06.865
*** MODULE NAME:() 2012-03-29 15:47:06.865
*** ACTION NAME:() 2012-03-29 15:47:06.865
error 27103 detected in background process
ORA-27103: internal error
Additional information: -1
Additional information: 1
*** 2012-03-29 15:47:06.865
MMAN (ospid: 16338): terminating the instance due to error 27103

结合alert和trace文件查询MOS,发现ORA-27103 when Memory target parameter is set to more than 3 GB [ID 743012.1]描述相符,是由于Bug:7272646引起.
鉴于朋友的数据库还升级过程中,所以给出的处理建议是先把memory_target改为2.8G,执行完升级操作,然后打上Patch:7272646
同时官方还给出了另一种解决方案:设置SHMMAX小于4G,个人不推荐;如果系统内存比较大,会出现多个内存段,影响系统性能

模拟ORA-04043并解决

创建两张模拟表

SQL> select * from v$version;
BANNER
------------------------------------------------------------------
Oracle9i Enterprise Edition Release 9.2.0.4.0 - Production
PL/SQL Release 9.2.0.4.0 - Production
CORE    9.2.0.3.0       Production
TNS for Linux: Version 9.2.0.4.0 - Production
NLSRTL Version 9.2.0.4.0 - Production
SQL> create table sys_xifenfei as
  2  select * from dba_tables;
Table created.
SQL> create table chf.chf_xifenfei as
  2  select * from dba_tables;
Table created.

启动数据库到mount状态查询表

SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup mount;
ORACLE instance started.
Total System Global Area  353441008 bytes
Fixed Size                   451824 bytes
Variable Size             184549376 bytes
Database Buffers          167772160 bytes
Redo Buffers                 667648 bytes
Database mounted.
SQL> desc dba_tables;
ERROR:
ORA-04043: object dba_tables does not exist
SQL> desc sys_xifenfei
ERROR:
ORA-04043: object sys_xifenfei does not exist
SQL> desc chf.chf_xifenfei
ERROR:
ORA-04043: object chf.chf_xifenfei does not exist

打开数据库查询

SQL> alter database open;
Database altered.
SQL> select count(*) from sys_xifenfei;
select count(*) from sys_xifenfei
                     *
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select count(*) from chf.chf_xifenfei;
  COUNT(*)
----------
       868
SQL> select count(*) from dba_tables;
select count(*) from dba_tables
                     *
ERROR at line 1:
ORA-00942: table or view does not exist

解决问题

SQL> alter system flush shared_pool;
System altered.
SQL> select count(*) from dba_tables;
  COUNT(*)
----------
       869
SQL> select count(*) from sys_xifenfei;
  COUNT(*)
----------
       867

MOS解释
ORA-4043 On DBA_* Views If They Are Described In Mount Stage [ID 296235.1]

Available workarounds are:
1) Don't describe the dba_* views at mount stage.
OR
2) If you issue DESC of any DBA_*views at mount stage,
    then shutdown and restart the DB instance.
OR
3) Flush the shared pool.
SQL> Alter system flush shared_pool;
and then reissue the failing command.

在10g中open库后提示也为类此ORA-04043: object dba_tables does not exist

关于9I中sga_max_size参数描述

不设置sga_max_size参数

SQL> show sga;
Total System Global Area  420549952 bytes
Fixed Size                   451904 bytes
Variable Size             201326592 bytes
Database Buffers          218103808 bytes
Redo Buffers                 667648 bytes
SQL> select sum(bytes)from v$sgastat;
SUM(BYTES)
----------
 420538688
SQL> !ipcs -m
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x9ba476a4 65536      oracle    640        440401920  65
SQL> alter system set db_cache_size=300M;
alter system set db_cache_size=300M
*
ERROR at line 1:
ORA-02097: parameter cannot be modified because specified value is invalid
ORA-00384: Insufficient memory to grow cache

1)当sga_max_size不设置时,数据库启动时,会使用数据库默认分配sga大小为初始化值
2)当sga_max_size不设置时,不能在线扩展组件内存大小(使得sga大于当前大小)

设置sga_max_size参数

SQL>  alter system set sga_max_size=600M scope=spfile;
System altered.
SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.
Total System Global Area  638654020 bytes
Fixed Size                   452164 bytes
Variable Size             419430400 bytes
Database Buffers          218103808 bytes
Redo Buffers                 667648 bytes
Database mounted.
Database opened.
SQL> !ipcs -m
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x9ba476a4 98304      oracle    640        658505728  65
SQL> select sum(bytes)from v$sgastat;
SUM(BYTES)
----------
 420538948
SQL> alter system set db_cache_size=405M;
System altered.
SQL> select 638654020/1024/1024 from dual;
638654020/1024/1024
-------------------
         609.067936
说明sga中剩余空闲内存0.01M
SQL> select 609.067936-sum(bytes)/1024/1024 from v$sgastat;
609.067936-SUM(BYTES)/1024/1024
-------------------------------
                     .010742244
继续增加组件大小
SQL> alter system set db_cache_size=416M;
System altered.
SQL> select sum(bytes)/1024/1024 from v$sgastat;
SUM(BYTES)/1024/1024
--------------------
          609.057194
SQL>  select 638654020/1024/1024 from dual;
638654020/1024/1024
-------------------
         609.067936
SQL> alter system set db_cache_size=417M;
alter system set db_cache_size=417M
*
ERROR at line 1:
ORA-02097: parameter cannot be modified because specified value is invalid
ORA-00384: Insufficient memory to grow cache
这里显示,当db_cache_size增加到415M的时候,sga只有0.01M剩余
但是直到db_cache_size增加到417的时候才报错

1)当sga有剩余时,可以动态调整sga中的部分组件(java_pool_size不能在线设置)
2)当sga没有剩余时,如果继续增加某组件的内存,在一定的范围内,sga会自动调整其他组件大小,以实用该值增加

关于sga_max_size总结
1)如果你的系统内存比较紧张,对停机时间要求不是特别严格,那可以不设置sga_max_size参数,这样在重启数据库设置sga组件的时候,不会因忘记设置sga_max_size而导致不能正常启动
2)如果你的系统内存充足,对停机有严格限制,那建议设置一个较大的sga_max_size,后续可以根据需求动态在线调整sga部分组件

DB2入门操作之一

1.DB2启动关闭

--关闭db2
[db2inst1@xifenfei ~]$ db2stop
03/28/2012 09:23:39     0   0   SQL1064N  DB2STOP processing was successful.
SQL1064N  DB2STOP processing was successful.
--开启db2
[db2inst1@xifenfei ~]$ db2start
03/28/2012 09:23:55     0   0   SQL1063N  DB2START processing was successful.
SQL1063N  DB2START processing was successful.

2.查看DB2数据库

[db2inst1@xifenfei ~]$ db2 list db directory
 System Database Directory
 Number of entries in the directory = 1
Database 1 entry:
 Database alias                       = TOOLSDB
 Database name                        = TOOLSDB
 Local database directory             = /home/db2inst1
 Database release level               = d.00
 Comment                              =
 Directory entry type                 = Indirect
 Catalog database partition number    = 0
 Alternate server hostname            =
 Alternate server port number         =

3.连接DB2数据库

[db2inst1@xifenfei ~]$ db2
(c) Copyright IBM Corporation 1993,2007
Command Line Processor for DB2 Client 9.7.4
You can issue database manager commands and SQL statements from the command
prompt. For example:
    db2 => connect to sample
    db2 => bind sample.bnd
For general help, type: ?.
For command help, type: ? command, where command can be
the first few keywords of a database manager command. For example:
 ? CATALOG DATABASE for help on the CATALOG DATABASE command
 ? CATALOG          for help on all of the CATALOG commands.
To exit db2 interactive mode, type QUIT at the command prompt. Outside
interactive mode, all commands must be prefixed with 'db2'.
To list the current command option settings, type LIST COMMAND OPTIONS.
For more detailed help, refer to the Online Reference Manual.
db2 => connect to TOOLSDB
   Database Connection Information
 Database server        = DB2/LINUX 9.7.4
 SQL authorization ID   = DB2INST1
 Local database alias   = TOOLSDB

4.查看数据库中包含包

db2 => list tables
Table/View                      Schema          Type  Creation time
------------------------------- --------------- ----- --------------------------
  0 record(s) selected.
db2 => create table t_xff (id int,name varchar(100))
DB20000I  The SQL command completed successfully.
db2 => list tables
Table/View                      Schema          Type  Creation time
------------------------------- --------------- ----- --------------------------
T_XFF                           DB2INST1        T     2012-03-28-09.29.54.572395
  1 record(s) selected.

5.常见DML操作

db2 =>  insert into t_xff values(1,'xifenfei')
DB20000I  The SQL command completed successfully.
db2 => insert into t_xff values(2,'www.xifenfei')
DB20000I  The SQL command completed successfully.
db2 => select * from t_xff
ID          NAME
----------- ---------------------------------------
          1 xifenfei
          2 www.xifenfei
  2 record(s) selected.
db2 => delete from t_xff where id=1
DB20000I  The SQL command completed successfully.
db2 => select * from t_xff
ID          NAME
----------- -----------------------------------------
          2 www.xifenfei
  1 record(s) selected.
db2 => quit
DB20000I  The QUIT command completed successfully.

Linux中安装DB2截图欣赏

DB在linux下面使用图形化界面安装非常方便,绝对不会像oracle那样的恶心,需要配置没完没了参数,简单到安装过程用户都是用过图形化界面给你,让你输入密码就可以了。现在分享一组安装截图

关于SMON_SCN_TIME若干问题说明

1.SMON_SCN_TIME表基础知识
0)作用
由smon收集scn和time映射关系,用于flashback/查询scn和time对应关系等操作

1)保留条数
官方文档给出说明instance number N * 12 times per hour * 24 hours * 5 days = 1440N rows,因为每次的时间间隔不是非常准确的5分钟,所以在具体的条数在实际生产环境中有一定的出入

2)采集和删除
smon进程没5分钟采集一次插入到SMON_SCN_TIME表中,同时将删除历史数据(超过5天前数据),采用下面语句
delete from smon_scn_time where thread=0 and time_mp = (select min(time_mp) from smon_scn_time where thread=0),如果有时候index出了问题,导致该语句执行很慢

3)当查询scn对应time,如果scn超过SMON_SCN_TIME表范围,将提示错误;或者查询time对应的scn,如果超过范围也同样报错。

2.当SMON_SCN_TIME表出现问题时,truncate操作语句

--找出CLUSTER
Select dbms_metadata.get_ddl('TABLE','SMON_SCN_TIME','SYS') FROM DUAL ;
9i
truncate CLUSTER "SYS"."SMON_SCN_TO_TIME";
10g
truncate  CLUSTER "SYS"."SMON_SCN_TO_TIME";
11g
truncate CLUSTER "SYS"."SMON_SCN_TO_TIME_AUX";

3.停止/开启smon进程收集scn信息

stop
alter system set events '12500 trace name context forever, level 10';
start
alter system set events '12500 trace name context off';

4.index异常处理

--找出index
Select index_name,index_type,owner from dba_indexes where table_name='SMON_SCN_TIME';
--对应index创建语句
Select dbms_metadata.get_ddl('INDEX','SMON_SCN_TIME_TIM_IDX','SYS') FROM DUAL;
--重建index
drop index smon_scn_time_scn_idx;
drop index smon_scn_time_tim_idx;
create unique index smon_scn_time_scn_idx on smon_scn_time(scn);
create unique index smon_scn_time_tim_idx on smon_scn_time(time_mp);
analyze table smon_scn_time validate structure cascade online;
--rebuild index
alter index sys.smon_scn_time_scn_idx rebuild online;
alter index sys.smon_scn_time_tim_idx rebuild online;
analyze table smon_scn_time validate structure cascade online;

补充知识点scn计算方法SCN=(SCN_WRP * 4294967296) + SCN_BAS

授权用户访问数据字典三种方式

在很多时候,希望给用户最小的权限,让其访问系统数据字典,检查数据库的运行状态。这种事情在乙方的工作中非常常见。下面介绍三种方法处理这个问题
0.select any table权限
这里说明select any table不能直接访问数据字典

SQL> conn / as sysdba
Connected.
SQL> create user xff_any identified by xifenfei;
User created.
SQL> grant connect,select any table to xff_any;
Grant succeeded.
SQL> conn xff_any/xifenfei
Connected.
SQL>  select count(*) from dba_users;
 select count(*) from dba_users
                      *
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select count(*) from chf.t_xff;
  COUNT(*)
----------
      2770

select any table默认情况下,只能访问业务的表,但是不能访问数据字典的数据。所以单纯的这个属性不能满足需求。

1.SELECT ANY DICTIONARY权限

SQL> conn / as sysdba
Connected.
SQL> create user xff_DICTIONARY identified by xifenfei;
User created.
SQL> grant connect to xff_DICTIONARY;
Grant succeeded.
SQL> conn xff_DICTIONARY/xifenfei
Connected.
SQL> select count(*) from dba_users;
select count(*) from dba_users
                     *
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> conn / as sysdba
Connected.
SQL> grant SELECT ANY DICTIONARY to xff_DICTIONARY;
Grant succeeded.
SQL> conn xff_DICTIONARY/xifenfei
Connected.
SQL> select count(*) from dba_users;
  COUNT(*)
----------
        32
SQL> select count(*) from chf.t_xff;
select count(*) from chf.t_xff
                         *
ERROR at line 1:
ORA-00942: table or view does not exist

这里可以看出SELECT ANY DICTIONARY权限只能访问数据字典,不能访问业务的表,访问业务的表需要另外授权

2.SELECT_CATALOG_ROLE角色

SQL> conn / as sysdba
Connected.
SQL> create user xff_CATALOG identified by xifenfei;
User created.
SQL> grant connect,SELECT_CATALOG_ROLE to xff_CATALOG;
Grant succeeded.
SQL> conn xff_CATALOG/xifenfei
Connected.
SQL> select count(*) from dba_users;
  COUNT(*)
----------
        33
SQL> select count(*) from chf.t_xff;
select count(*) from chf.t_xff
                         *
ERROR at line 1:
ORA-00942: table or view does not exist

这里可以看出SELECT_CATALOG_ROLE权限只能访问数据字典,不能访问业务的表,访问业务的表需要另外授权

3.O7_DICTIONARY_ACCESSIBILITY参数

SQL> conn / as sysdba
Connected.
SQL> create user xff_O7 identified by xifenfei;
User created.
SQL> grant connect to xff_o7;
Grant succeeded.
SQL> alter system set O7_DICTIONARY_ACCESSIBILITY=true;
alter system set O7_DICTIONARY_ACCESSIBILITY=true
                 *
ERROR at line 1:
ORA-02095: specified initialization parameter cannot be modified
SQL> alter system set O7_DICTIONARY_ACCESSIBILITY=true scope=spfile;
System altered.
SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.
Total System Global Area  368263168 bytes
Fixed Size                  1345016 bytes
Variable Size             306186760 bytes
Database Buffers           54525952 bytes
Redo Buffers                6205440 bytes
Database mounted.
Database opened.
SQL> conn xff_o7/xifenfei
Connected.
SQL> select count(*) from dba_users;
  COUNT(*)
----------
        34

这里通过O7_DICTIONARY_ACCESSIBILITY和SELECT ANY TABLE权限,实现访问业务数据和数据字典