2014-10-18 67 views

回答

12
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 varyingid 列。但这是一个错误,因为我总是给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) ; 
+1

的'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

相关问题