我正在尝试查看是否有任何方法可以使用一条语句从表中的所有 varchar 列中删除回车符和换行符。
我知道我们可以使用类似下面的方法对单个列执行此操作
select regexp_replace(field, E'[\\n\\r]+', ' ', 'g' )
在那种情况下,我需要每一列都有一个,除非有任何简单的方法,否则我不想这样做。
感谢您的帮助!
最佳答案
您可以创建一个 plpgsql 函数来执行动态 SQL,或者直接通过 DO 运行它,如下例(将 my_table
替换为您的表的名称`):
do $$declare _q text; _table text = '<mytable>';
begin
select 'update '||attrelid::regclass::text||E' set\n'||
string_agg(' '||quote_ident(attname)||$q$ = regexp_replace($q$||quote_ident(attname)||$q$, '[\n\r]+', ' ', 'g')$q$, E',\n' order by attnum)
into _q
from pg_attribute
where attnum > 0 and atttypid::regtype::text in ('text', 'varchar')
group by attrelid
having attrelid = _table::regclass;
raise notice E'Executing:\n\n%', _q;
-- uncomment this line when happy with the query:
-- execute _q;
end;$$;
关于regex - 如何使用 Postgresql 删除表中所有列的回车符和换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38003739/