本文介绍了在PostgreSQL中将列数据类型从Text更改为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下查询将列的数据类型从文本更改为整数,但出现错误:

I am using the following query to change the data type of a column from text to integer but getting error:

 alter table a.attend alter column terminal 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
列。但这是一个错误,因为我总是给 integers 作为 id 。因此,使用 varchar 是一个不好的做法。因此,让我们尝试将列类型更改为 integer

You can see from the above table that I have used the data type – character varying for idcolumn. But it was a mistake because I am always giving integers as id. So using varchar here is a bad practice. So let’s try to change the column type to integer.

ALTER TABLE test ALTER COLUMN id TYPE integer;

但是它返回:

这意味着我们不能简单地更改数据类型,因为列中已经存在数据。由于数据的类型是个字符,而 Postgres不能期望它是整数,尽管我们只输入了整数。所以现在,按照Postgres的建议,我们可以使用 USING 表达式将数据转换为整数。

That means we can’t simply change the data type because data is already there in the column. Since the data is of type character varying Postgres can't expect it as integer though we entered integers only. So now, as Postgres suggested we can use the USING expression to cast our data into integers.

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

有效。

所以您应该使用

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

这篇关于在PostgreSQL中将列数据类型从Text更改为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:38
查看更多