数据库通过存储过程批量添加注释(模板为oracle)

在操作数据库时,我们时常需要给数据库中的表名以及字段名添加注释,如果去写comment语句,或者是直接拼出来一条一条去执行,亦或者使用一些可视化工具去添加,都太过于繁琐。

在此背景下,我想到了一个比较方便的、节省成本的方法与大家分享,就是维护一个注释表,然后编写一个存储过程,存储过程中自动拼成一条一条的comment sql语句,然后利用游标去循环执行,效率非常高,而且维护起来也方便,具体操作步骤如下:

1、建注释表

create table TABCOL_COMMENTS
(
  TAB_NAME     VARCHAR2(500),
  TAB_COMMENTS VARCHAR2(500),
  COL_NAME     VARCHAR2(500),
  COL_COMMENTS VARCHAR2(500)
)
tablespace BIGDATA_STG
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 256
    next 256
    minextents 1
    maxextents unlimited
    pctincrease 0
  );
-- Add comments to the columns 
comment on column TABCOL_COMMENTS.TAB_NAME
  is '表名';
comment on column TABCOL_COMMENTS.TAB_COMMENTS
  is '表注释';
comment on column TABCOL_COMMENTS.COL_NAME
  is '字段名';
comment on column TABCOL_COMMENTS.COL_COMMENTS
  is '字段注释';

2、编写存储过程

create or replace procedure PORC_COMMENT is
 v_log varchar2(1000);
 CURSOR CUR_SQL IS

with A as
(select upper(tab.tab_name) as tab_name, tab.tab_comments, upper(tab.col_name) as col_name,tab.col_comments
from tabcol_comments tab),

--字段注释
B as
(SELECT 'comment on column ' || tab_name || '.' || col_name || ' is ''' || col_comments || ''''  as sqls
from A),

--表注释
C as
(select'comment on table ' || tab_name || ' is ''' || tab_comments || '''' as sqls
from A),
D as 
(select distinct sqls from C)
select sqls from B
union all
select sqls from D;

begin

execute immediate 'truncate table tabcol_comments_log';
for cur_s in CUR_SQL LOOP
insert into tabcol_comments_log (v_log) values(cur_s.sqls);
commit;
execute immediate cur_s.sqls;

end LOOP;

END PORC_COMMENT;

猜你喜欢

转载自blog.csdn.net/weixin_35353187/article/details/107769296
今日推荐