加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在PostgreSQL中将列数据类型从Text更改为Integer [复制]

发布时间:2020-12-13 16:19:12 所属栏目:百科 来源:网络整理
导读:参见英文答案 Rails Migrations: tried to change the type of column from string to integer6个 我使用以下查询将列的数据类型从文本更改为整数但获取错误: alter table a.attend alter column terminal TYPE INTEGER ; ERROR: column “terminal” canno
参见英文答案 > Rails Migrations: tried to change the type of column from string to integer6个
我使用以下查询将列的数据类型从文本更改为整数但获取错误:
alter table a.attend alter column terminal TYPE INTEGER ;

ERROR: column “terminal” cannot be cast automatically to type integer

create table test(id varchar );
insert into test values('1');
insert into test values('11');
insert into test values('12');

select * from test

 --Result--
 id
 character varying
--------------------------
 1
 11
 12

您可以从上表中看到我使用了数据类型 – 字符因id而异
柱.但这是一个错误,因为我总是把整数作为id.所以在这里使用varchar是一种不好的做法.所以让我们尝试将列类型更改为整数.

ALTER TABLE test ALTER COLUMN id TYPE integer;

但它返回:

ERROR: column “id” cannot be cast automatically to type integer SQL
state: 42804 Hint: Specify a USING expression to perform the
conversion

这意味着我们不能简单地更改数据类型,因为列中已存在数据.由于数据类型为字符变化,Postgres不能指望它为整数,尽管我们只输入了整数.所以现在,正如Postgres建议我们可以使用USING表达式将数据转换为整数.

ALTER TABLE test ALTER COLUMN id  TYPE integer USING (id::integer);

有用.

所以你应该使用

alter table a.attend alter column terminal TYPE INTEGER  USING (terminal::integer) ;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读