PostgreSQL DBA(154) - pgAdmin(bool转换为smallint)

本节介绍了PostgreSQL中的列类型转换:bool类型转换为smallint。

转换过程
1.使用psql中的\help alter table命令找到修改列类型的语法:

[local:/data/run/pg12]:5120 pg12@testdb=# \help alter table
Command:     ALTER TABLE
Description: change the definition of a table
Syntax:
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
    action [, ... ]
...
where action is one of:
    ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
    DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
    ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
    ALTER [ COLUMN ] column_name SET DEFAULT expression
    ALTER [ COLUMN ] column_name DROP DEFAULT
    ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL
    ALTER [ COLUMN ] column_name ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]
    ALTER [ COLUMN ] column_name { SET GENERATED { ALWAYS | BY DEFAULT } | SET sequence_option | RESTART [ [ WITH 
] restart ] } [...]
    ALTER [ COLUMN ] column_name DROP IDENTITY [ IF EXISTS ]
    ALTER [ COLUMN ] column_name SET STATISTICS integer
    ALTER [ COLUMN ] column_name SET ( attribute_option = value [, ... ] )
    ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] )
    ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }

2.执行转换

[local:/data/run/pg12]:5120 pg12@testdb=# drop table t_bool;
ERROR:  table "t_bool" does not exist
[local:/data/run/pg12]:5120 pg12@testdb=# create table t_bool(col bool);
CREATE TABLE
[local:/data/run/pg12]:5120 pg12@testdb=# alter table t_bool alter column col type smallint;
ERROR:  column "col" cannot be cast automatically to type smallint
HINT:  You might need to specify "USING col::smallint".
[local:/data/run/pg12]:5120 pg12@testdb=#

提示指定使用”USING col::smallint”,翻看PG的语法:

ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]

USING后面跟的是expression表达式,可以理解为如何转换的表达式,因此执行以下语句:

[local:/data/run/pg12]:5120 pg12@testdb=# alter table t_bool alter column col type smallint using col::int::smallint;
ALTER TABLE

DONE!成功转换。
实际上,还可以更简化:

[local:/data/run/pg12]:5120 pg12@testdb=# alter table t_bool alter column col type smallint using col::int;
ALTER TABLE

因为int到smallint是有转换的,不需要明确的int::smallint,但为了说明转换过程,加上该转换会清晰许多。

附录
测试脚本如下:

drop table t_bool;
create table t_bool(col bool);
alter table t_bool alter column col type smallint;
alter table t_bool alter column col type smallint using col::int::smallint;
请使用浏览器的分享功能分享到微信等