SQL 在 PostgreSQL 中将列数据类型从文本更改为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26439033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change column datatype from Text to Integer in PostgreSQL
提问by Newbie
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 ;
ERROR: column "terminal" cannot be cast automatically to type integer
错误:列“终端”无法自动转换为整数类型
回答by Vivek S.
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
You can see from the above table that I have used the data type – character varying
for id
column. 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
.
你可以从上面的表格中看到,我已经使用的数据类型-character varying
为id
列。但这是一个错误,因为我总是给integers
as id
。所以varchar
在这里使用是一种不好的做法。因此,让我们尝试将列类型更改为integer
.
ALTER TABLE test ALTER COLUMN id TYPE integer;
But it returns:
但它返回:
ERROR: column “id” cannot be cast automatically to type integer SQL state: 42804 Hint: Specify a USING expression to perform the conversion
错误:列“id”无法自动转换为类型整数 SQL 状态:42804 提示:指定一个 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.
这意味着我们不能简单地更改数据类型,因为数据已经存在于列中。由于数据类型为character varying
Postgres,虽然我们只输入了整数,但不能期望它是整数。所以现在,正如 Postgres 建议的那样,我们可以使用USING
表达式将我们的数据转换为整数。
ALTER TABLE test ALTER COLUMN id TYPE integer USING (id::integer);
It Works.
有用。
So you should use
所以你应该使用
alter table a.attend alter column terminal TYPE INTEGER USING (terminal::integer) ;