这篇文章主要介绍“PostgreSQL中的bool类型转换为smallint的方法是什么”,在日常操作中,相信很多人在PostgreSQL中的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;
到此,关于“PostgreSQL中的bool类型转换为smallint的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!