oracle 外键无索引导致锁

摘自TOM大师的语句, 外键不加索引

SELECT TABLE_NAME,
owner CONSTRAINT_NAME,
CNAME1 || NVL2(CNAME2, ',' || CNAME2, NULL) ||
NVL2(CNAME3, ',' || CNAME3, NULL) ||
NVL2(CNAME4, ',' || CNAME4, NULL) ||
NVL2(CNAME5, ',' || CNAME5, NULL) ||
NVL2(CNAME6, ',' || CNAME6, NULL) ||
NVL2(CNAME7, ',' || CNAME7, NULL) ||
NVL2(CNAME8, ',' || CNAME8, NULL) COLUMNS
FROM (SELECT B.owner,
B.TABLE_NAME,
B.CONSTRAINT_NAME,
MAX(DECODE(POSITION, 1, COLUMN_NAME, NULL)) CNAME1,
MAX(DECODE(POSITION, 2, COLUMN_NAME, NULL)) CNAME2,
MAX(DECODE(POSITION, 3, COLUMN_NAME, NULL)) CNAME3,
MAX(DECODE(POSITION, 4, COLUMN_NAME, NULL)) CNAME4,
MAX(DECODE(POSITION, 5, COLUMN_NAME, NULL)) CNAME5,
MAX(DECODE(POSITION, 6, COLUMN_NAME, NULL)) CNAME6,
MAX(DECODE(POSITION, 7, COLUMN_NAME, NULL)) CNAME7,
MAX(DECODE(POSITION, 8, COLUMN_NAME, NULL)) CNAME8,
COUNT(*) COL_CNT
FROM (SELECT SUBSTR(TABLE_NAME, 1, 30) TABLE_NAME,
SUBSTR(CONSTRAINT_NAME, 1, 30) CONSTRAINT_NAME,
SUBSTR(COLUMN_NAME, 1, 30) COLUMN_NAME,
POSITION
FROM DBA_CONS_COLUMNS) A,
DBA_CONSTRAINTS B
WHERE A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
AND B.CONSTRAINT_TYPE = 'R'
GROUP BY B.TABLE_NAME, B.CONSTRAINT_NAME, B.owner) CONS
WHERE COL_CNT > ALL (SELECT COUNT(*)
FROM DBA_IND_COLUMNS I
WHERE I.TABLE_NAME = CONS.TABLE_NAME
AND I.COLUMN_NAME IN (CNAME1,
CNAME2,
CNAME3,
CNAME4,
CNAME5,
CNAME6,
CNAME7,
CNAME8)
AND I.COLUMN_POSITION < = CONS.COL_CNT
GROUP BY I.INDEX_NAME);

 

--等待事件---P1 P2 P3 

select ash .SAMPLE_TIME ,
ash .EVENT ,
ash .SESSION_ID ,
ash .BLOCKING_SESSION ,
ash .P1TEXT ,
ash .P1 ,
ash .P2TEXT ,
ash .p2 ,
ash .p3text ,
ash .p3 ,
ash .SESSION_STATE ,
ash .SQL_OPNAME ,
ash .SQL_ID
--ash.*
from v$active_session_history ash
where ash .SAMPLE_TIME >
to_date ( '20200519 17:50:00' , 'yyyymmdd HH24:MI:SS' )
and ash .SAMPLE_TIME <
to_date ( '20200519 18:10:00' , 'yyyymmdd HH24:MI:SS' )
and ash .WAIT_CLASS < > 'Idle'
-- and ash .EVENT like 'enq: TM - contention'
order by sample_time desc;

 

--结论 

  1.      外键无索引锁无cascade时,update/delete父表,会在语句级别级联一个mode为4的S锁到子表,其中delete多少行就会级联多少次
  2.     外键无索引有cascade时,update父表仍会在语句级别级联mode为4的S锁到子表,delete时会先获取mode为5的SSX锁,在将其转换成mode为3的SX锁,而且删除多少行就会涉及到多少次转换 
  3.  外键有索引无cascade时,update/delete不会在语句级级联锁到子表,最终会持有父表和子表上的mode为3的SX锁(无索引时只有有cascade的delete时最终会持有子表上的SX锁) 
  4. 外键有索引有cascade时,与无cascade表现相同

 --原文:http://blog.itpub.net/30345407/viewspace-2689108/

posted @ 2020-05-20 14:47  钱若梨花落  阅读(360)  评论(0编辑  收藏  举报