动态生成修改默认值SQL脚本

今天遇到一个问题, 就是在割接生产的脚本你类似如下
create table ** as select * from tableName@DB_LINK

但是割接过来的数据丢失了默认值,而其它外键索引主键我都有单独的脚本,唯一默认值未准备脚本,所以写了个下面的动作脚本来生成可以修改默认值的动态脚本:

DECLARE
  --定义一个字符串数组类型
  TYPE tableNamesArray IS TABLE OF VARCHAR2(200);
  --所有表名
  tableNames tableNamesArray := tableNamesArray('TEST_TAB,TEST_US',
                                               
                                                );

  result    varchar2(4000);
  tableName varchar2(200);
  ownerName varchar2(20);
  icnt      integer;
BEGIN

  --循环插入数据
  FOR i IN 1 .. tableNames.COUNT LOOP
    icnt      := instr(tableNames(i), ',');
    tableName := upper(subStr(tableNames(i), 1, icnt - 1));
    ownerName := upper(subStr(tableNames(i),
                              icnt + 1,
                              length(tableNames(i))));
 
    for rec in (select a.COLUMN_NAME cn, a.DATA_DEFAULT cd
                  from sys.all_tab_columns a
                 where a.TABLE_NAME = tableName
                   and a.OWNER = ownerName
                   and a.DATA_DEFAULT is not null) loop
      result := 'alter table OD.' || tableName || ' modify(' || rec.cn ||
                ' default ' || rec.cd || ');';
      dbms_output.put_line(result);
      result := '';
    end loop;
  end loop;

EXCEPTION
  WHEN others THEN
    DBMS_OUTPUT.put_line('执行生成INSERT语句出现异常!' || substr(sqlerrm, 1, 2000));
END;

你可能感兴趣的:(sql)