【PostgreSQL】修改表的字段类型时遇到的问题

注意事项:

1、最好先把字段的默认值去掉,因为修改后的字段类型与默认值不匹配时会报错;

2、BOOLEAN直接转为SMALLINT是不行的,需要先转为INTEGER再转SMALLINT;

1、ALTER TABLE中改变数据类型时USING的用法

在修改表字段类型的时候使用Using来进行显示的转换类型。

原文说明:

SET DATA TYPE 
  This form changes the type of a column of a table. Indexes and simple table constraints involving the column willbe automatically converted to use the new column type by reparsing the originally supplied expression. The optional COLLATE clause specifies a collation for the new column; if omitted, the collation is the default for the new column type. The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

  大致意思是:转换类型的时候有隐含类型转换的时候,会自动转换,如果没有,那么就必须使用using指定一下转换规则。

1. 建表

create table 101(id integer);

2. 插入数据

insert into tb10 select generate_series(1,5);

3. 把id的int变为varchar

postgres=# alter table tb101 alter id type varchar;
ALTER TABLE

因为int转varchar有隐式的转换,故可以自动转换过去。

postgres=# \d tb101
          Table "public.tb101"
 Column |       Type        | Modifiers 
--------+-------------------+-----------
 id     | character varying |

4. 把id的varchar变为int

postgres=# alter table tb101 alter id type int;
ERROR:  column "id" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

在没有隐式的转换下,就需要指定Using来显示的转换。

5. 使用Using进行类型转换

postgres=# alter table tb101 alter id type int using id::int;
ALTER TABLE
postgres=# \d tb101
     Table "public.tb101"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 

————————————————

2、报错:cannot be cast automatically to type integer

如果你直接使用可视化工具修改一个varchar字段为int类型的时候,可能会报错,

这里就需要自己去写一个语句去修改了

调整执行语句:ALTER TABLE table_name ALTER COLUMN column_name TYPE integer USING(column_name::integer);

这样的话,修改就可以正常的修改了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值