如何修剪PostgreSQL数据库中所有表中每列的尾随空格

1 sql postgresql dynamic-sql


我在这个任务就是我需要努力修剪所有尾随空格从每所有的在我的PostgreSQL Database.

   
我有

update tbl_sale set product=trim(product) where product LIKE '% '
Run Code Online (Sandbox Code Playgroud)

这将TRIMproduct tbl_sale.


在我的数据库 中有137个表,如果它有尾随空格,那么我的数据库中的TRIM所有是否可能?

Viv*_* S. 6

以下查询将返回所有可能有也可能没有尾随空格的及其 .注意:我假设您的所有桌面名称都以.

tbl_

 select 
     table_name,COLUMN_NAME
 from 
     INFORMATION_SCHEMA.COLUMNS 
 where 
     table_name LIKE 'tbl_%' and (data_type='text' or data_type='character varying')
Run Code Online (Sandbox Code Playgroud)

要获取所有表的UPDATE 查询,请使用以下选择

select 
       'UPDATE '||quote_ident(c.table_name)||' SET '||c.COLUMN_NAME||'=TRIM('||quote_ident(c.COLUMN_NAME)||')  
        WHERE '||quote_ident(c.COLUMN_NAME)||' ILIKE ''% '' ' as script
from (
        select 
           table_name,COLUMN_NAME
        from 
           INFORMATION_SCHEMA.COLUMNS 
        where 
           table_name LIKE 'tbl_%' and (data_type='text' or data_type='character varying')
     ) c
Run Code Online (Sandbox Code Playgroud)

这将返回行想
update tbl_sale set product=trim(product) where product LIKE '% '更新所有列的所有.


最后,
使用此方法更新具有尾随空格的中的所有.database

do $$
declare
    selectrow record;
begin
for selectrow in
select 
       'UPDATE '||quote_ident(c.table_name)||' SET '||c.COLUMN_NAME||'=TRIM('||c.COLUMN_NAME||')  WHERE '||quote_ident(c.COLUMN_NAME)||' ILIKE ''% '' ' as script
from (
       select 
          table_name,COLUMN_NAME
       from 
          INFORMATION_SCHEMA.COLUMNS 
       where 
          table_name LIKE 'tbl_%'  and (data_type='text' or data_type='character varying' )
     ) c
loop
execute selectrow.script;
end loop;
end;
$$;
Run Code Online (Sandbox Code Playgroud)

将上述方法包装成一个Function,以便将来使用更方便

create function rm_trail_spaces() returns void as 
   $$

    declare
        selectrow record;
    begin
    for selectrow in
    select 
           'UPDATE '||quote_ident(c.table_name)||' SET '||quote_ident(c.COLUMN_NAME)||'=TRIM('||quote_ident(c.COLUMN_NAME)||')  WHERE '||quote_ident(c.COLUMN_NAME)||' ILIKE ''% '' ' as script
    from (
           select 
              table_name,COLUMN_NAME
           from 
              INFORMATION_SCHEMA.COLUMNS 
           where 
              table_name LIKE 'tbl_%'  and (data_type='text' or data_type='character varying' )
         ) c
    loop
    execute selectrow.script;
    end loop;
    end;
  $$
  language plpgsql   
Run Code Online (Sandbox Code Playgroud)

用法: SELECT rm_trail_spaces()