代码改变世界

小知识:后台执行Oracle创建索引免受会话中断影响

2020-08-03 22:45  AlfredZhao  阅读(518)  评论(0编辑  收藏  举报

因为客户环境的堡垒机经常会莫名的断开连接,也不是简单的超时,因为有时候即使你一直在操作,也可能会断。
这样对于操作一些耗时长且中途中断可能会导致异常的操作就很危险,而最简单的避免方法就是将其写到脚本中,nohup挂到后台去执行。
本文以在线创建索引为例,比如给jingyu用户下T1表创建table_name,table_type两个字段的联合索引。

1.编辑创建索引的脚本并后台执行

注意sysdba执行,需要明确指定业务用户jingyu,一般要求业务低峰期online创建,parallel并行度根据当时系统资源实际使用情况来调整,最终建完索引成功后一定要记得去掉索引的并行度设置。 创建索引之前要大概预估下索引的大小,并结合索引指定存放的表空间剩余是否充足,同时也需要注意数据库的临时表空间要充足。 在一些特定场景下,还可以使用nologging选项进一步提升速度(前提就是数据库没有开启force logging才可以)。
vi createidx.sh

sqlplus / as sysdba <<EOF
set timing on
CREATE INDEX jingyu.IDX_T1 ON jingyu.T1(table_name,table_type) tablespace DBS_D_JINGYU parallel 8 online;
alter INDEX jingyu.IDX_T1 noparallel;
EOF

nohup sh createidx.sh > createidx.log &

关于索引的大小、临时表空间使用等预估可以通过预查看创建索引的语句来获得比较准确的参考:

--这里没加online是因为测试online不会显示具体的索引预估大小
explain plan for CREATE INDEX jingyu.IDX_T1 ON jingyu.T1(table_name,table_type) tablespace DBS_D_JINGYU;
--查看执行计划
set lines 1000 pages 1000
select * from table(dbms_xplan.display());

PLAN_TABLE_OUTPUT
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Plan hash value: 2186317495

---------------------------------------------------------------------------------
| Id  | Operation              | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------
|   0 | CREATE INDEX STATEMENT |        |     8 |   152 |     3   (0)| 00:00:01 |
|   1 |  INDEX BUILD NON UNIQUE| IDX_T1 |       |       |            |          |
|   2 |   SORT CREATE INDEX    |        |     8 |   152 |            |          |
|   3 |    TABLE ACCESS FULL   | T1     |     8 |   152 |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------------

Note
-----
   - estimated index size: 65536  bytes

14 rows selected.

2.查看输出日志确认创建成功

[oracle@jystdrac1 ~]$ tail -20f createidx.log 

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, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

sys@CRMDB> sys@CRMDB> 
Index created.

Elapsed: 00:01:31.41
sys@CRMDB> 
Index altered.

Elapsed: 00:00:05.64
sys@CRMDB> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options