简体   繁体   English

PostgreSQL 9.6 更改某个数据类型表中的所有列

[英]Change all columns in table of a certain data type in PostgreSQL 9.6

It seems like several months ago I came across a SO question covering this but I can't seem to find it now.似乎几个月前我遇到了一个关于这个的问题,但我现在似乎找不到它。

Basically, I want to do two things.基本上,我想做两件事。

First, a number of tables were made with several columns numeric(20,2) and I want to just change them all to numeric .首先,许多表格由几列numeric(20,2) ,我想将它们全部更改为numeric The statement is simple enough for one column:该语句对于一列来说足够简单:

ALTER TABLE table_name
ALTER COLUMN code
TYPE numeric;

Takes care of that.照顾那个。

Second, on these columns I want to remove any trailing zeros:其次,在这些列上,我想删除所有尾随零:

UPDATE table_name
SET code = replace(replace(code::text, '.50', '.5'), '.00', '')::numeric;

Having difficulty figuring out how to automate it so I only have to specify the table and it will clean up the table.很难弄清楚如何自动化它,所以我只需要指定表格,它就会清理表格。 Pretty sure this is possible.很确定这是可能的。

You can find all of the columns with the data type that you want to change with a statement like:您可以使用以下语句找到具有要更改的数据类型的所有列:

select column_name, table_name
from information_schema.columns
where data_type='numeric'
    and numeric_precision = 20
    and numeric_scale = 2;

You can iterate over the result with a custom function or with a DO command such as:您可以使用自定义函数或 DO 命令迭代结果,例如:

do $$
declare
t record;
begin
    for t IN select column_name, table_name
            from information_schema.columns
            where data_type='numeric'
                and numeric_precision = 20
                and numeric_scale = 2;
    loop
        execute 'alter table ' || t.table_name || ' alter column ' || t.column_name || ' type numeric';
    end loop;
end$$;

Also, to remove trailing zeroes, a more general solution is to cast the value to float or double precision and then back to numeric, eg:此外,要删除尾随零,更通用的解决方案是将值转换为浮点或双精度,然后再转换回数字,例如:

set code = cast(cast(code as double precision) as numeric);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM