当前位置:Gxlcms > mysql > oracle数据库中替换字符串

oracle数据库中替换字符串

时间:2021-07-01 10:21:17 帮助过:132人阅读

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

做应用时遇到过这么个问题,数据库录入了一些基础数据,有时候可能会把数据库中所有包含“联通”的字符都替换为“电信”,类似这么个功能吧,写了个简单的替换程序,当然如果你不想替换某些表就修改一个替换规则
如果数据比较重要,调用之前最好备份下数据,替换之后不可逆哦 Oracle
  1. create or replace procedure STR_REPLACE_ALL(oldStr in varchar2,newStr in varchar2) is
  2. TABLE_NAME VARCHAR2(45);--表名
  3. COLUMN_NAME VARCHAR2(100);--字段名
  4. SQL_STR VARCHAR2(200);--动态执行的SQL
  5. type cur_type is ref cursor;--定义游标类型
  6. cursor_columns cur_type;--查询字段游标
  7. cursor cursor_tables is--查询表游标
  8. select table_name from user_tables;
  9. begin
  10. open cursor_tables;
  11. loop
  12. --遍历所有的数据库表
  13. fetch cursor_tables into TABLE_NAME;
  14. exit when cursor_tables%notfound;
  15. DBMS_OUTPUT.put_line(TABLE_NAME);
  16. --遍历当前表所有字符型字段
  17. SQL_STR := 'select COLUMN_NAME from user_tab_columns where TABLE_NAME='''||TABLE_NAME||''' and DATA_TYPE in (''CHAR'',''VARCHAR2'')';
  18. open cursor_columns for SQL_STR;
  19. loop
  20. fetch cursor_columns into COLUMN_NAME;
  21. exit when cursor_columns%notfound;
  22. --DBMS_OUTPUT.put_line('---'||COLUMN_NAME);
  23. --替换更新当前字段
  24. SQL_STR := 'update '||TABLE_NAME||' set '||COLUMN_NAME||' =replace('||COLUMN_NAME||','''||oldStr||''','''||newStr||''')';
  25. --DBMS_OUTPUT.put_line(SQL_STR);
  26. EXECUTE IMMEDIATE SQL_STR;
  27. commit;
  28. end loop;
  29. end loop;
  30. end STR_REPLACE_ALL;

人气教程排行