oracle可重复执行脚本

2019-07-14  本文已影响0人  忧从中来

       之前的一次项目上线,使用CTAS的方式进行扩表,涉及到表的删除。由于自动化部署工具的问题,数据库脚本执行了两次。导致数据库表被删除(万幸有备份)。
       抛开自动化部署工具的问题,这一次数据库脚本也存在问题,一个足够健壮的线上数据库脚本应该是可以被重复执行的。下面给出oracle一些常用的可重复执行脚本示例。

表创建

declare
    create_str         varchar(5000) := 'create table TABLE_NAME ...';
    count_flag         number;
begin
    select count(*) into count_flag from user_tables where table_name = 'TABLE_NAME';
    if count_flag > 0 then
        execute immediate create_str;
    else
        execute immediate 'drop table TABLE_NAME';
        execute immediate create_str;
    end if;
end

表字段添加

declare
    add_str         varchar(5000) := 'alter table TABLE_NAME add COLUMN_NAME varchar(32)';
    count_flag         number;
begin
    select count(*) into count_flag from user_tab_columns 
        where table_name = 'TABLE_NAME' and column_name = 'COLUMN_NAME ';
    if count_flag < 1 then
        execute immediate add_str;
    end if;
end

原理很简单,就是利用各种用户视图,判断当前执行结果是否已存在,然后再决定是否执行。虽然简单,但在工程实践中具有较重要意义,需要掌握。

上一篇 下一篇

猜你喜欢

热点阅读