我在这个任务就是我需要努力修剪所有尾随空格从每列所有的表在我的PostgreSQL Database.
我有
update tbl_sale set product=trim(product) where product LIKE '% '
Run Code Online (Sandbox Code Playgroud)
这将TRIM在product 列于表 tbl_sale.
在我的数据库 中有137个表,如果它有尾随空格,那么我的数据库中的TRIM所有列是否可能?
以下查询将返回所有可能有也可能没有尾随空格的表及其 列.注意:我假设您的所有桌面名称都以.
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()
| 归档时间: |
|
| 查看次数: |
5225 次 |
| 最近记录: |