Oracle quickly adds fields to all tables

The following example is to add the field "IMPORT_DATE" and add the field comment "Date of storage" for all tables whose names contain'_OPT' in the current user of the database.

declare
  --需要执行的SQL字符串
  v_alter_sqlstr  varchar2(500);
  -- 游标
  cursor c_result is 
  select 'alter table ' || t.OBJECT_NAME  || ' add IMPORT_DATE date default sysdate;
          comment on column ' || t.OBJECT_NAME ||'.IMPORT_DATE is ''入库日期''; 
        ' as alter_sqlstr
    from user_objects t where t.OBJECT_TYPE='TABLE' and t.object_name like '%_OPT';

  -- 定义一个与游标一样的变更
  v_result c_result%rowtype;
begin
  open c_result;
    loop
      fetch c_result into v_result;  
      exit when c_result%notfound;
      v_alter_sqlstr := v_result.alter_sqlstr;
      dbms_output.put_line(v_alter_sqlstr); -- 可单独将SQL从output窗口提取出来执行
      
      -- 执行修改
      --execute immediate v_alter_sqlstr;   
    end loop;
  close c_result;
exception
  when others then
    begin
      dbms_output.put_line('异常:' || 'sqlcode:' || sqlcode || ' sqlerrm : ' ||sqlerrm );
    end;  
end;

You can directly execute the above SQL statement to add fields to the table, or you can print out the SQL statement that needs to be executed and execute it separately.

It is recommended to print out the SQL statement to be executed first, and then execute the SQL script manually after checking that there is no problem, so as to be safer.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/109156003