如何使用Postgresql删除表中所有列的回车符和换行符?

时间:2016-06-24 00:03:09

标签: regex postgresql

我试图查看是否有任何方法可以使用一个语句从表中的所有varchar列中删除运输和新行。

我知道我们可以使用下面的内容为单个列执行此操作

select regexp_replace(field, E'[\\n\\r]+', ' ', 'g' )

在这种情况下,我需要每列都有一个,除非有任何简单的方法,否则我不想这样做。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以创建一个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;$$;
相关问题