因为特殊原因,需要将数据库里所有表的所有字段中带有某字样的数据替换成另外一个数据,当然有很多种实现方法,我就直接写了个数据库函数解决了,话不多说上代码。
create or replace function myReplace(nowChar varchar,afterChar varchar)
returns text LANGUAGE plpgsql as $$
declare
resultV text;
tablesName varchar;
columnsName varchar;
tableCursor refcursor;
columnCursor refcursor;
begin
open tableCursor for execute 'select tablename from pg_tables where tablename !~ ''(^pg.*)|(^sql.*)''';
loop
fetch tableCursor into tablesName;
if found then
open columnCursor for execute 'select column_name from information_schema.columns where table_name ='''||tablesName||''' and data_type = ''character varying''';
loop
if found then
fetch columnCursor into columnsName;
resultV := resultV || columnsName || ',';
if columnsName is not null then
execute 'update '||tablesName||' set '||columnsName||' = replace('||columnsName||','''||nowChar||''','''||afterChar||''')';
raise notice 'columnsName:%',columnsName;
end if;
else
close columnCursor;
exit;
end if;
end loop;
else
close tableCursor;
exit;
end if;
end loop;
return resultV;
end;
$$
逻辑是 首先查询所有数据库表,然后遍历每个表的每一个字段将符合条件的字段替换为想要替换的内容。
这里有几个注意点:
一、库里有一些以pg、sql开头的表是自带的隐藏表,不需要替换
二、替换内容时,我只替换了数据类型为character varying类型的数据,可以根据自己需要更改