2014-04-18 50 views
2

比方說,我有一個表call_log,它有一個名爲duration的列。讓我們進一步假裝,當我把表放在一起時,我犯了一個錯誤,使duration varchar列而不是一個數字。現在我無法在該列上正確排序。我要重命名的列,所以我的問題... ...如何更改數據列的數據類型

ALTER TABLE call_log MODIFY (duration NUMBER); 

,但我得到...

ORA-01439: column to be modified must be empty to change datatype. 

我的表已經使用並具有數據!我不想丟失數據。如何修改列的數據類型而不丟失數據?

回答

5

使用正確的數據類型創建臨時列,將數據複製到新列,刪除舊列,重命名新列以匹配舊列的名稱。

ALTER TABLE call_log ADD (duration_temp NUMBER); 
UPDATE call_log SET duration_temp = duration; 
ALTER TABLE call_log DROP COLUMN duration; 
ALTER TABLE call_log RENAME COLUMN duration_temp TO duration; 

這個答案的想法來自Oracle's forums

1

以前的解決方案是優秀的,但是如果你不想改變call_log表結構中的列訂單,那麼下面的步驟是這樣的:

create table temp_call_log as select * from call_log; /* temp backup table for call_log */ 
UPDATE call_log SET duration = null; 
/*check,... be sure.... then commit*/ 
commit; 
ALTER TABLE call_log MODIFY duration NUMBER; 
UPDATE call_log c SET c.duration = (select t.duration from temp_call_log t where t.primarykey_comumn = c.primarykey_column); 
/*check,... be sure.... then commit*/ 
commit; 
drop table temp_call_log; 

注1:改變primarykey_comumn與主鍵表call_log。

note2:此解決方案假定您的數據大小不大。