通过shell分析表依赖的层级关系(r3笔记第97天)

时间:2022-05-04
本文章向大家介绍通过shell分析表依赖的层级关系(r3笔记第97天),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在平时的工作环境中,总会有一些表会存在依赖关系,比如我们有三张表customer,用户表subscriber,账户表account 其中客户可以有多个用户或者账户,subscriber表和account表中就存在外键customer_id指向了customer表。 这种情况下表的依赖关系就如下所示: customer subscriber account 如果表中的层级关系更为复杂,如果能够得到一个很清晰的依赖关系表。在做一些重要的操作时就能运筹帷幄。避免很多不必要的麻烦。 使用shell脚本分析表依赖的层级关系脚本如下:

sqlplus -s $DB_CONN_STR@$SH_DB_SID <<EOF
set pages 1000
set echo off
set feedback off
create  table table_depency_rel as
(
select   
          p.table_name  parent_table_name ,   
          p.owner p_owner,  
          c.table_name  child_table_name ,  
          c.owner c_owner  
     from  user_constraints p, user_constraints c  
    where p.constraint_type IN  ('P','U') AND  
          c.constraint_type = 'R' AND  
           p.constraint_name = c.r_constraint_name
          group by  p.table_name,p.owner, c.table_name, c.owner
)
;
--alter table  table_depency_rel modify(p_owner null);
alter table table_depency_rel  modify(parent_table_name null);
insert into table_depency_rel 
(
select  null,null,parent_table_name,p_owner from table_depency_rel 
where  parent_table_name not in (select child_table_name from table_depency_rel group  by child_table_name)group by parent_table_name,p_owner 
);
set echo  on
set feedback on
col table_node format a50
col level_code format  a5
select decode(level,1,'<--'||level,level)||'-' level_code ,  lpad('-',level*3-1,'--')||'||'||t.child_table_name||'('||level||')' table_node  from table_depency_rel t
connect by prior t.child_table_name   =t.parent_table_name 
start with t.child_table_name in(select  child_table_name from table_depency_rel where parent_table_name is null group by  child_table_name)
--order by parent_table_name desc;
set feedback off
set echo off
drop table table_depency_rel;
EOF
exit

自己在反复模拟一些场景之后总结了如上的脚本。 我们来通过如下的方式运行脚本,查看system下的表依赖关系。

ksh  showdepency.sh

LEVEL TABLE_NODE
-----  --------------------------------------------------
<--1-  --||AQ$_INTERNET_AGENTS(1)
2-     -----||AQ$_INTERNET_AGENT_PRIVS(2)
<--1- --||DEF$_DESTINATION(1)
2-     -----||DEF$_CALLDEST(2)
2-    -----||REPCAT$_REPSCHEMA(2)
<--1-  --||MVIEW$_ADV_LOG(1)
2-    -----||MVIEW$_ADV_AJG(2)
3-     --------||MVIEW$_ADV_FJG(3)
4-     -----------||MVIEW$_ADV_GC(4)
......

可以很清晰的看到显示的层级关系,有1,2,3,4 其中1是根节点,2,3,4是依赖表,4依赖3,3依赖2,依此类推。