2014-10-18 142 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

相關問題