修改oracle數據庫字段類型,處理ORA-01439錯誤

測試環境:

drop table foo;
create table foo (col_name varchar2(5));
insert into foo values('1');
insert into foo values('12');
insert into foo values('33445');
commit;
create index idx1 on foo (col_name);
select * from foo;
desc foo

解決方法

 1. 建立新表

根據當前表結構建立新表,修改新表字段,將原數據灌進來,刪除舊錶,將新表rename爲舊錶名  sql

create table new as select * from foo where 1=2;
alter table new modify (col_name number(5));
insert into new select * from foo;
drop table foo;
rename new to foo;

若是原表有索引,觸發器、外鍵等須要新建。 oracle

2.  使用CTAS來轉換

oracle 的使用查詢建立表的功能建立一個新表包含原來的數據,命令以下: 
create table new
as 
select [其餘的列], 
 to_number(Char_Col) col_name
from foo;


而後drop 原表,新表改名爲原表: 
drop table foo; 
rename new to foo;
與方法1同樣要注意新建相關對象。
 

3. 建立臨時字段替換

新建一個臨時字段,把要修改的字段的內容備份到臨時字段後清空原字段,而後再修改類型,以後再把臨時字段的內容複製到修改後的字段,最後刪除臨時字段
alter table foo add(tmp_col number(5));
update foo set tmp_col = to_number(col_name);
update foo set col_name = null; --此處要當心啊,原數據全沒了,必定要保證上一步正確執行

alter table foo modify (col_name number(5));
update foo set col_name = tmp_col;
alter table foo drop column tmp_col;
相關文章
相關標籤/搜索