分类目录归档:ORACLE 12C

Oracle 12C TABLE ACCESS BY INDEX ROWID BATCHED

从Oracle 12C开始执行计划中可能会出现TABLE ACCESS BY INDEX ROWID BATCHED,官方的解释:TABLE ACCESS BY INDEX ROWID BATCHED:means that the database retrieves a few rowids from the index, and then attempts to access rows in block order to improve the clustering and reduce the number of times that the database must access a block.主要意思:对于一个块中多个rowid,通过批量减少访问快的次数.而作为12.1的新特性,数据库是通过_optimizer_batch_table_access_by_rowid来控制的

数据库版本12.1

SQL> select * from v$version;

BANNER                                                                               CON_ID
-------------------------------------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production              0
PL/SQL Release 12.1.0.2.0 - Production                                                    0
CORE    12.1.0.2.0      Production                                                        0
TNS for IBM/AIX RISC System/6000: Version 12.1.0.2.0 - Production                         0
NLSRTL Version 12.1.0.2.0 - Production                                                    0

TABLE ACCESS BY INDEX ROWID BATCHED执行计划

SQL> set autot traceonly exp stat;
SQL> var  b1 number;
SQL> set lines 150
SQL> set pages 10000
SQL> exec :b1:=18868701138;

PL/SQL procedure successfully completed.

SQL> SELECT BRAND_ID FROM T_USERTYPE_FULLNO WHERE BILL_ID= LTRIM(:B1 ,'0') AND ROWNUM < 2;


Execution Plan
----------------------------------------------------------
Plan hash value: 942613467

-----------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name               | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                    |     1 |    15 |     2   (0)| 00:00:01 |
|*  1 |  COUNT STOPKEY                       |                    |       |       |            |          |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| XIFENFEI           |     1 |    15 |     2   (0)| 00:00:01 |
|*  3 |    INDEX RANGE SCAN                  | IND_XIFENFEI       |     1 |       |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM<2)
   3 - access("BILL_ID"=LTRIM(:B1,'0'))


Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          5  consistent gets
          0  physical reads
          0  redo size
        559  bytes sent via SQL*Net to client
        552  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed

_optimizer_batch_table_access_by_rowid参数为true

SQL> col name for a32
SQL> col value for a24
col description for a70
set linesize 150
select a.ksppinm name,b.ksppstvl value,a.ksppdesc description
SQL> SQL> SQL>   2    from x$ksppi a,x$ksppcv b
  3   where a.inst_id = USERENV ('Instance')
  4     and b.inst_id = USERENV ('Instance')
  5     and a.indx = b.indx
  6     and upper(a.ksppinm) LIKE upper('%&param%')
  7  order by name
  8  /
Enter value for param: _optimizer_batch_table_access_by_rowid
old   6:    and upper(a.ksppinm) LIKE upper('%&param%')
new   6:    and upper(a.ksppinm) LIKE upper('%_optimizer_batch_table_access_by_rowid%')

NAME                                 VALUE                    DESCRIPTION
------------------------------------- ------------------------ ----------------------------------------------
_optimizer_batch_table_access_by_rowid TRUE                     enable table access by ROWID IO batching

设置_optimizer_batch_table_access_by_rowid为false,执行计划由TABLE ACCESS BY INDEX ROWID BATCHED变为TABLE ACCESS BY INDEX ROWID

SQL> set autot traceonly exp stat;
SQL> var  b1 number;
SQL> set lines 150
SQL> set pages 10000
SQL> exec :b1:=18868701138;

PL/SQL procedure successfully completed.

SQL> alter session set "_optimizer_batch_table_access_by_rowid"=false;

Session altered.

SQL> SELECT BRAND_ID FROM XIFENFEI WHERE BILL_ID= LTRIM(:B1 ,'0') AND ROWNUM < 2;


Execution Plan
----------------------------------------------------------
Plan hash value: 2797551150

---------------------------------------------------------------------------------------------------
| Id  | Operation                    | Name               | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |                    |     1 |    15 |     2   (0)| 00:00:01 |
|*  1 |  COUNT STOPKEY               |                    |       |       |            |          |
|   2 |   TABLE ACCESS BY INDEX ROWID| XIFENFEI           |     1 |    15 |     2   (0)| 00:00:01 |
|*  3 |    INDEX RANGE SCAN          | IND_XIFENFEI       |     1 |       |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM<2)
   3 - access("BILL_ID"=LTRIM(:B1,'0'))


Statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
          5  consistent gets
          0  physical reads
          0  redo size
        559  bytes sent via SQL*Net to client
        552  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed

optimizer_features_enable修改为11.2之后,_optimizer_batch_table_access_by_rowid会联锁变为fasle

SQL> alter session set optimizer_features_enable = '11.2.0.3';

Session altered.

SQL> col name for a52
col value for a24
col description for a50
set linesize 150
select a.ksppinm name,b.ksppstvl value,a.ksppdesc description
  from x$ksppi a,x$ksppcv b
 where a.inst_idSQL> SQL> SQL> SQL>   2    3   = USERENV ('Instance')
   and b.inst_id = USERENV ('Instance')
   and a.indx = b.indx
   and upper(a.ksppinm) LIKE upper('%&param%')
order by name
  4    5    6    7    8  /
Enter value for param: _optimizer_batch_table_access_by
old   6:    and upper(a.ksppinm) LIKE upper('%&param%')
new   6:    and upper(a.ksppinm) LIKE upper('%_optimizer_batch_table_access_by%')

NAME                                       VALUE          DESCRIPTION
------------------------------------------ -------------- -----------------------------------------
_optimizer_batch_table_access_by_rowid     FALSE          enable table access by ROWID IO batching

这里可以看出来,在调整optimizer_features_enable参数后,会直接影响某些数据库相关的优化器参数,例如:_optimizer_batch_table_access_by_rowid

发表在 ORACLE 12C, Oracle性能优化 | 标签为 , , | 评论关闭

InMemory评估利器—Oracle Database InMemory Advisor

我想大家都可能有一个疑问,数据库从以前版本升级到12C,计划使用in-memory特性,那我怎么评估哪些表放进去合适,放进去后,整体性能又会提升多少,需要in-memory内存为多大?这些问题如果人工去判断不一定准确,而且可能有很多遗落,Oracle也考虑到了这一点,因此发布了Oracle Database InMemory Advisor,从而来比较简单的实现数据库使用In-Memory简单配置.Oracle Database InMemory Advisor主要通过DBMS_INMEMORY_ADVISOR包分析 Active Session History (ASH), Automatic Workload Repository (AWR) and SQL Tuning Sets (STS)信息进行分析,给出建议.

Oracle Database InMemory Advisor使用前提
1.数据库版本为11.2.0.3及其以上版本(compatibility>=11.2.0.3)
2.需要有Database Tuning pack liscense支持(仅仅是liscense,不是功能)

安装Oracle Database InMemory Advisor

[oracle@localhost xff]$ unzip imadvisor.zip 
Archive:  imadvisor.zip
  inflating: instimadv.sql           
  inflating: dbmsimadv.sql           
  inflating: prvtimadv.plb           
  inflating: dbmsimadvint.plb        
  inflating: prvtimadvint.plb       
  inflating: schmimadv.sql           
  inflating: imadvisor_version.sql   
  inflating: imadvisor_load_report_templates.sql  
  inflating: imadvisor_clone_view.sql  
  inflating: imadvisor_analyze_and_report.sql  
  inflating: imadvisor_spool_debug.sql  
  inflating: imadvisor_export.sql    
  inflating: imadvisor_DataPump.sql  
  inflating: imadvisor_awr_augment_export.sql  
  inflating: imadvisor_awr_augment_import.sql  
  inflating: imadvisor_awr_augment_tables.sql  
  inflating: imadvisor_fetch_recommendations.sql  
[oracle@localhost xff]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.4.0 Production on Wed Mar 18 16:21:08 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> @instimadv
Welcome to the Oracle Database In-Memory Advisor (DBMS_INMEMORY_ADVISOR)
installation.

The Oracle Database In-Memory Advisor is licensed as part of the Oracle Tuning Pack.
Do you currently have a valid Oracle Tuning Pack license with this database (Y/N)? Y

DBMS_INMEMORY_ADVISOR uses Active Session History (ASH), Automatic Workload
Repository (AWR) and optionally SQL Tuning Sets (STS) to determine which
tables, partitions and subpartitions to place In Memory for optimized analytics
processing performance.  DBMS_INMEMORY_ADVISOR produces a recommendation report
and a SQLPlus script to implement its recommendations.

This installation script will create user IMADVISOR and add object
definitions to the schema including the DBMS_INMEMORY_ADVISOR package.  This
installation script creates user IMADVISOR using the
IDENTIFIED BY password method. If you prefer to use either the
IDENTIFIED EXTERNALLY or IDENTIFIED GLOBALLY method, abort this installation
by pressing ^C. Then create user IMADVISOR using your preferred
method.  Add no objects to the IMADVISOR schema.  Then run this
installation script again.

These actions will be taken on the database to which you are currently
connected.

Please enter the connection ID for the current database?
qsng      

This installation script creates a new Oracle database user and schema
named IMADVISOR for the operation of DBMS_INMEMORY_ADVISOR...

Please enter the password for user IMADVISOR?

For confirmation, please re-enter the password for user IMADVISOR?

Available tablespaces:

TABLESPACE_NAME
------------------------------
FSDATA
MYDATA
SYSAUX
SYSTEM
TEMP
UNDOTBS1
USERS
Please enter the default tablespace name for user IMADVISOR?
users
The In-Memory Advisor uses the Oracle directory object IMADVISOR_DIRECTORY
by default.
If you wish to create the IMADVISOR_DIRECTORY object, please enter an OS host
directory path for the IMADVISOR_DIRECTORY object.
If not, please press ENTER to continue.
? /tmp/xff
Connecting to IMADVISOR @ qsng..
Enter password: 
Connected.
No errors.
No errors.
No errors.
No errors.
No errors.
No errors.

DBMS_INMEMORY_ADVISOR installation successful.

Users who will use the DBMS_INMEMORY_ADVISOR package must be GRANTed
EXECUTE on the DBMS_INMEMORY_ADVISOR package.

Please enter a comma separated list of Oracle Database users to whom
you wish EXECUTE on the DBMS_INMEMORY_ADVISOR package to be GRANTed?
SYS

GRANT EXECUTE ON dbms_inmemory_advisor TO SYS

While logged in as IMADVISOR or with sufficient privileges, you can
GRANT EXECUTE ON DBMS_INMEMORY_ADVISOR to additional users as needed.

DBMS_INMEMORY_ADVISOR installation and setup complete.

Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

Oracle Database InMemory Advisor生成报告

[oracle@localhost xff]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.4.0 Production on Wed Mar 18 16:30:57 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> @imadvisor_analyze_and_report


Specify the IM task name
The IM Advisor generates a report as  imadvisor_<taskname>.html file
in the current working directory
The sql file is generated as imadvisor_sql_<taskname>.sql

Enter value for im_task_name: xifenfei

IM Task name Specified: xifenfei
Enter begin time for report:

--    Valid input formats:
--      To specify absolute begin time:
--        [MM/DD[/YY]] HH24:MI[:SS]
--        Examples: 02/23/03 14:30:15
--                  02/23 14:30:15
--                  14:30:15
--                  14:30
--      To specify relative begin time: (start with '-' sign)
--        -[HH24:]MI
--        Examples: -1:15  (SYSDATE - 1 Hr 15 Mins)
--                  -25    (SYSDATE - 25 Mins)

Enter value for begin_time: -3
Report begin time specified: -3

old 102:   lbtime_in  := nvl('&&begin_time', '-60');
new 102:   lbtime_in  := nvl('-3', '-60');
old 104:   :btime := to_char( begin_time, '&&imadvisor_time_format' );
new 104:   :btime := to_char( begin_time, 'YYYY-MON-DD HH24:MI:SS.FF' );

Enter duration in minutes starting from begin time:
Defaults to SYSDATE - begin_time

Enter value for duration: 
Report duration specified:
old   8:   begin_time := to_timestamp(:btime, '&&imadvisor_time_format');
new   8:   begin_time := to_timestamp(:btime, 'YYYY-MON-DD HH24:MI:SS.FF');
old  18:   duration   := nvl('&&duration', since_begin_time);
new  18:   duration   := nvl('', since_begin_time);
old  29:   :etime := to_char( end_time, '&&imadvisor_time_format' );
new  29:   :etime := to_char( end_time, 'YYYY-MON-DD HH24:MI:SS.FF' );

Using 2015-MAR-18 16:28:22.000000000 as report begin time
Using 2015-MAR-18 16:31:22.000000000 as report end time

IM Advisor: Adding Statistics..
IMADVISOR: Finished Adding Statistics
IMADVISOR: Finished Executing the task
IM Advisor: Generating Recommendations..

imadvisor_xifenfei.html

imadvisor_sql_xifenfei.html

imadvisor_object_xifenfei.html

imadvisor_xifenfei.sql
'Fetching recommendation files for task xifenfei'
IM Advisor generated report in imadvisor_xifenfei.html
IM Advisor genreated DDL script in imadvisor_xifenfei.sql
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@localhost xff]$ ls -ltr *xifenfei*
-rw-r--r-- 1 oracle oinstall   887 Mar 18 16:33 imadvisor_xifenfei.sql
-rw-r--r-- 1 oracle oinstall 30175 Mar 18 16:33 imadvisor_xifenfei.html
-rw-r--r-- 1 oracle oinstall 13576 Mar 18 16:33 imadvisor_sql_xifenfei.html
-rw-r--r-- 1 oracle oinstall  8931 Mar 18 16:33 imadvisor_object_xifenfei.html
-rw-r--r-- 1 oracle oinstall  3405 Mar 18 16:33 imadvisor_auxiliary_xifenfei.html

这里输入的Task name为:xifenfei,Oracle Database InMemory Advisor结果
imadvisor_xifenfei.html是InMemory Advisor的一个整体描述
imadvisor_xifenfei.sql是InMemory Advisor生成的表级别的INMEMORY语句,可以直接通过@方式执行,或者修改后执行
imadvisor_sql_xifenfei.html主要是InMemory Advisor中关于sql的分析报告
imadvisor_object_xifenfei.html是InMemory Advisor中建议InMemory处理的对象分析报告
imadvisor_auxiliary_xifenfei.html 是一个辅助的总结

卸载Oracle Database InMemory Advisor

[oracle@localhost ~]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.4.0 Production on Wed Mar 18 21:55:49 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> drop user imadvisor cascade;

User dropped.

补充内容
1.在某些情况下,可能无法直接创建用户imadvisor,或者创建目录imadvisor_directory,可以通过类似命令创建,并修改instimadv.sql脚本屏蔽掉交互式安装

create user IMADVISOR identified by Oracle_123 DEFAULT TABLESPACE system;
CREATE OR REPLACE DIRECTORY imadvisor_directory AS '/tmp/xff/txt';
GRANT READ, WRITE ON DIRECTORY imadvisor_directory TO IMADVISOR;

2.在执行@imadvisor_analyze_and_report生成报告,可能会遇到ORA-24817: Unable to allocate the given chunk for current lob operation,解决方案为:

1. Copy the original script to a new location to serve as a backup.
2. Edit the script imadvisor_fetch_recommendations.sql and change the line in the script:
SET LONGCHUNKSIZE 2000000000
to
SET LONGCHUNKSIZE 32767
3. Save and run the script.

参考文档
Oracle Database InMemory Advisor (Doc ID 1965343.1)
Using Inmemory Advisor Errors When Running Imadvisor_analyze_and_report (Doc ID 1987462.1)

发表在 ORACLE 12C | 标签为 , , | 评论关闭

ORACLE 12C 新特性Identity Columns—实现ORACLE自增长列功能

在ORACLE 12C以前的版本中,如果要实现列自增长,需要通过序列+触发器实现,到了12C ORACLE 引进了Identity Columns新特性,从而实现了列自增长功能,和mysql,sql server类似功能.
使用语法
ORACLE 12C IDENTITY
GENERATED ALWAYS AS IDENTITY方式测试

C:\Users\ffcheng>sqlplus chf/xifenfei@pdb

SQL*Plus: Release 12.1.0.2.0 Production on 星期二 3月 10 14:34:46 2015

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

上次成功登录时间: 星期五 12月 19 2014 21:00:26 +08:00

连接到:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing opt
ions

XFF_PDB@CHF> select * from v$version;

BANNER                                                 CON_ID
-------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.          0
1.0.2.0 - 64bit Production

PL/SQL Release 12.1.0.2.0 - Production                      0
CORE    12.1.0.2.0      Production                          0
TNS for 64-bit Windows: Version 12.1.0.2.0 - Produ          0
ction

NLSRTL Version 12.1.0.2.0 - Production                      0

XFF_PDB@CHF>  create table t_xifenfei (id number GENERATED ALWAYS AS IDENTITY,na
me varchar2(100));

表已创建。

XFF_PDB@CHF> select object_name,object_type from user_objects;

OBJECT_NAME     OBJECT_TYPE
--------------- -----------------------
ISEQ$$_91982    SEQUENCE
T_XIFENFEI      TABLE

XFF_PDB@CHF> set long 10000
XFF_PDB@CHF> select dbms_metadata.get_ddl('TABLE','T_XIFENFEI') FROM DUAL;

DBMS_METADATA.GET_DDL('TABLE','T_XIFENFEI')
--------------------------------------------------------------------------------
  CREATE TABLE "CHF"."T_XIFENFEI"
   (    "ID" NUMBER GENERATED ALWAYS AS IDENTITY MINVALUE 1 MAXVALUE
   9999999999999999999999999999 INCREMENT BY 1 START WITH 1 
   CACHE 20 NOORDER  NOCYCLE  NOT NULL ENABLE,
        "NAME" VARCHAR2(100)
   ) SEGMENT CREATION DEFERRED
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  TABLESPACE "INMEMORY"

XFF_PDB@CHF> INSERT INTO T_XIFENFEI VALUES(1,'WWW.XIFNEFEI.COM');
INSERT INTO T_XIFENFEI VALUES(1,'WWW.XIFNEFEI.COM')
*
第 1 行出现错误:
ORA-32795: 无法插入到“始终生成”身份列


XFF_PDB@CHF> INSERT INTO T_XIFENFEI(name) VALUES('WWW.XIFNEFEI.COM');

已创建 1 行。

XFF_PDB@CHF> INSERT INTO T_XIFENFEI(name) VALUES('WWW.orasos.COM');

已创建 1 行。

XFF_PDB@CHF> commit;

提交完成。

XFF_PDB@CHF> col name for a30
XFF_PDB@CHF> select * from t_xifenfei;

        ID NAME
---------- ------------------------------
         1 WWW.XIFNEFEI.COM
         2 WWW.orasos.COM

XFF_PDB@CHF> update t_xifenfei set id=3 where id=2;
update t_xifenfei set id=3 where id=2
                      *
第 1 行出现错误:
ORA-32796: 无法更新“始终生成”身份列

XFF_PDB@CHF> delete from t_xifenfei where id=1;

已删除 1 行。

XFF_PDB@CHF> commit;

提交完成。

XFF_PDB@CHF> select ISEQ$$_91982.nextval from dual;

   NEXTVAL
----------
         3

XFF_PDB@CHF> INSERT INTO T_XIFENFEI(name) VALUES('WWW.ORASOS.COM');

已创建 1 行。

XFF_PDB@CHF> commit;

提交完成。

XFF_PDB@CHF> select * from t_xifenfei;

        ID NAME
---------- ------------------------------
         2 WWW.orasos.COM
         4 WWW.ORASOS.COM

XFF_PDB@CHF> ALTER SESSION SET EVENTS '10046 TRACE NAME CONTEXT FOREVER, LEVEL 1
2';

会话已更改。

XFF_PDB@CHF>  select value from v$diag_info where name='Default Trace File';

VALUE
--------------------------------------------------------------------------------

D:\APP\FFCHENG\diag\rdbms\xff\xff\trace\xff_ora_10628.trc

XFF_PDB@CHF> INSERT INTO T_XIFENFEI(name) VALUES('WWW.XIFENFEI.COM');

已创建 1 行。

XFF_PDB@CHF> COMMIT;

提交完成。

--跟踪trace文件
PARSING IN CURSOR #688719640 len=55 dep=0 uid=103 oct=2 lid=103 tim=15129490112 hv=961646460 
ad='7ff05d11a18' sqlid='21uzyjhwp33vw'
INSERT INTO T_XIFENFEI(name) VALUES('WWW.XIFENFEI.COM')
END OF STMT
PARSE #688719640:c=15600,e=18909,p=0,cr=44,cu=0,mis=1,r=0,dep=0,og=1,plh=2541165129,tim=15129490112
EXEC #688719640:c=0,e=347,p=0,cr=1,cu=5,mis=0,r=1,dep=0,og=1,plh=2541165129,tim=15129490731
STAT #688719640 id=1 cnt=0 pid=0 pos=1 obj=0 op='LOAD TABLE CONVENTIONAL  T_XIFENFEI (cr=1 pr=0 pw=0 time=296 us)'
STAT #688719640 id=2 cnt=1 pid=1 pos=1 obj=91983 op='SEQUENCE  ISEQ$$_91982 (cr=0 pr=0 pw=0 time=89 us)'
WAIT #688719640: nam='SQL*Net message to client' ela= 2 driver id=1413697536 #bytes=1 p3=0 obj#=-1 tim=15129490971

XFF_PDB@CHF> alter table t_xifenfei2 modify(id number GENERATED ALWAYS AS IDENTI
TY MINVALUE 1 MAXVALUE 99999999999999 INCREMENT BY 1 START WITH 1 CACHE  100);

表已更改。

XFF_PDB@CHF> drop sequence ISEQ$$_91982;
drop sequence ISEQ$$_91982
              *
第 1 行出现错误:
ORA-32794: 无法删除系统生成的序列

XFF_PDB@CHF> drop table t_xifenfei;

表已删除。

XFF_PDB@CHF> select object_name,object_type from user_objects where object_name=
'ISEQ$$_91982';

OBJECT_NAME          OBJECT_TYPE
-------------------- -----------------------
ISEQ$$_91982         SEQUENCE

XFF_PDB@CHF> select object_name,object_type from user_objects where object_name=
'ISEQ$$_91982';

OBJECT_NAME          OBJECT_TYPE
-------------------- -----------------------
ISEQ$$_91982         SEQUENCE

XFF_PDB@CHF> purge table t_xifenfei;

表已清除。

XFF_PDB@CHF> select object_name,object_type from user_objects where object_name=
'ISEQ$$_91982';

未选定行

这里的出来几个结论:
1. GENERATED ALWAYS AS IDENTITY 列无法人工指定值和修改该值
2. GENERATED IDENTITY 本质也是通过sequence实现
3. GENERATED IDENTITY 中sequence不能单独被删除
4. GENERATED IDENTITY 中的表删除,如果存在回收站中,该sequence依然存储,如果表被彻底删除,则sequence也被删除
5. GENERATED IDENTITY 中的sequence可以通过select 语句查询
6. 通过alert table 语句来修改GENERATED IDENTITY 的sequence相关值

GENERATED BY DEFAULT AS IDENTITY方式测试

XFF_PDB@CHF>  create table t_xifenfei2 (id number GENERATED BY DEFAULT AS IDENTI
TY,name varchar2(100)) tablespace users;

表已创建。

XFF_PDB@CHF> insert into t_xifenfei2 values (1,'www.xifenfei.com');

已创建 1 行。

XFF_PDB@CHF> insert into t_xifenfei2(name) values ('www.orasos.com');

已创建 1 行。

XFF_PDB@CHF> col name for a20
XFF_PDB@CHF> select * from t_xifenfei2;

        ID NAME
---------- --------------------
         1 www.xifenfei.com
         1 www.orasos.com

XFF_PDB@CHF> insert into t_xifenfei2 values (null,'www.xifenfei.com');
insert into t_xifenfei2 values (null,'www.xifenfei.com')
                                *
第 1 行出现错误:
ORA-01400: 无法将 NULL 插入 ("CHF"."T_XIFENFEI2"."ID")


XFF_PDB@CHF> desc t_xifenfei2
 名称                                      是否为空? 类型
 ----------------------------------------- -------- ---------------------------

 ID                                        NOT NULL NUMBER
 NAME                                               VARCHAR2(100)

得出结论:
1. GENERATED BY DEFAULT AS IDENTITY方式不能在该列中插入null值
2. GENERATED BY DEFAULT AS IDENTITY方式可以指定具体值插入

GENERATED BY DEFAULT ON NULL AS IDENTITY方式测试

XFF_PDB@CHF>  create table t_xifenfei3 (id number GENERATED BY DEFAULT on null A
S IDENTITY,name varchar2(100)) tablespace users;

表已创建。

XFF_PDB@CHF> desc t_xifenfei3
 名称                                      是否为空? 类型
 ----------------------------------------- -------- ----------------------------

 ID                                        NOT NULL NUMBER
 NAME                                               VARCHAR2(100)

XFF_PDB@CHF> insert into t_xifenfei3 values (null,'www.xifenfei.com');

已创建 1 行。

XFF_PDB@CHF> select * from t_xifenfei3;

        ID NAME
---------- --------------------
         1 www.xifenfei.com

测试结论:GENERATED BY DEFAULT ON NULL AS IDENTITY的列上可以查询null值,只是默认转换为对应的sequence值

传统自增长列实现方法

XFF_PDB@CHF> create table t_xifenfei4 (id number,name varchar2(100)) tablespace
users;

表已创建。

XFF_PDB@CHF> create sequence xff_sequence
  2  increment by 1
  3  minvalue 1
  4  nomaxvalue
  5  start with 1
  6  cache 20
  7  order;

序列已创建。

XFF_PDB@CHF> create or replace trigger xifenfei_id
  2  before insert on t_xifenfei4
  3  for each row
  4  begin
  5  select xff_sequence.nextval into :new.id from dual;
  6  end;
  7  /

触发器已创建

XFF_PDB@CHF> insert into t_xifenfei4(name) values('www.xifenfei.com');

已创建 1 行。

XFF_PDB@CHF> select * from t_xifenfei4;

        ID NAME
---------- --------------------
         1 www.xifenfei.com
发表在 ORACLE 12C | 标签为 , | 评论关闭