我使用下面的查询来改变从文本列的数据类型为整数,但得到的错误:从文本更改列数据类型为整数PostgreSQL中
alter table a.attend alter column terminal TYPE INTEGER ;
ERROR: column "terminal" cannot be cast automatically to type integer
我使用下面的查询来改变从文本列的数据类型为整数,但得到的错误:从文本更改列数据类型为整数PostgreSQL中
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
你可以看到从上面的表中我已经使用了数据类型 - character varying
为id
列。但这是一个错误,因为我总是给integers
作为id
。所以在这里使用varchar
是一个不好的做法。所以我们尝试将列类型更改为integer
。
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
这意味着我们不能简单地更改数据类型,因为数据已经出现在列。由于数据类型为character varying
尽管我们只输入了整数,但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) ;
的'USING'条款,如果没有隐含的赋值转换的源和目标类型之间定义时,才需要。详细信息[here](http://stackoverflow.com/questions/10343383/rails-migrations-tried-to-change-the-type-of-column-from-string-to-integer/10343444#10343444)和[here ](http://stackoverflow.com/questions/21045909/generate-series-of-dates-using-date-type-as-input/21051215#21051215)。 – 2014-10-18 11:44:32