Home  >  Article  >  Database  >  oracle数据库中替换字符串

oracle数据库中替换字符串

WBOY
WBOYOriginal
2016-06-07 14:57:261205browse

做应用时遇到过这么个问题,数据库录入了一些基础数据,有时候可能会把数据库中所有包含“联通”的字符都替换为“电信”,类似这么个功能吧,写了个简单的替换程序,当然如果你不想替换某些表就修改一个替换规则 如果数据比较重要,调用之前最好备份下数据,替

做应用时遇到过这么个问题,数据库录入了一些基础数据,有时候可能会把数据库中所有包含“联通”的字符都替换为“电信”,类似这么个功能吧,写了个简单的替换程序,当然如果你不想替换某些表就修改一个替换规则
如果数据比较重要,调用之前最好备份下数据,替换之后不可逆哦 Oracle
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;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn