时间:2021-07-01 10:21:17 帮助过:132人阅读
做应用时遇到过这么个问题,数据库录入了一些基础数据,有时候可能会把数据库中所有包含“联通”的字符都替换为“电信”,类似这么个功能吧,写了个简单的替换程序,当然如果你不想替换某些表就修改一个替换规则 如果数据比较重要,调用之前最好备份下数据,替
做应用时遇到过这么个问题,数据库录入了一些基础数据,有时候可能会把数据库中所有包含“联通”的字符都替换为“电信”,类似这么个功能吧,写了个简单的替换程序,当然如果你不想替换某些表就修改一个替换规则
- create or replace procedure STR_REPLACE_ALL(oldStr in varchar2,newStr in varchar2) is
- TABLE_NAME VARCHAR2(45);--表名
- COLUMN_NAME VARCHAR2(100);--字段名
- SQL_STR VARCHAR2(200);--动态执行的SQL
- type cur_type is ref cursor;--定义游标类型
- cursor_columns cur_type;--查询字段游标
- cursor cursor_tables is--查询表游标
- select table_name from user_tables;
- begin
- open cursor_tables;
- loop
- --遍历所有的数据库表
- fetch cursor_tables into TABLE_NAME;
- exit when cursor_tables%notfound;
- DBMS_OUTPUT.put_line(TABLE_NAME);
- --遍历当前表所有字符型字段
- SQL_STR := 'select COLUMN_NAME from user_tab_columns where TABLE_NAME='''||TABLE_NAME||''' and DATA_TYPE in (''CHAR'',''VARCHAR2'')';
- open cursor_columns for SQL_STR;
- loop
- fetch cursor_columns into COLUMN_NAME;
- exit when cursor_columns%notfound;
- --DBMS_OUTPUT.put_line('---'||COLUMN_NAME);
- --替换更新当前字段
- SQL_STR := 'update '||TABLE_NAME||' set '||COLUMN_NAME||' =replace('||COLUMN_NAME||','''||oldStr||''','''||newStr||''')';
- --DBMS_OUTPUT.put_line(SQL_STR);
- EXECUTE IMMEDIATE SQL_STR;
- commit;
- end loop;
- end loop;
- end STR_REPLACE_ALL;