测试环境:


1 2 3 4 5 6 7 8 9


​ ​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为旧表名

​


1 2 3 4 5


​ ​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;​ ​


如果原表有索引,触发器、外键等需要新建。



2.  使用CTAS来转换


oracle 的使用查询创建表的功能创建一个新表包含原来的数据,命令如下:


1 2 3 4 5


​ ​create​ ​​ ​ table​ ​​ ​ new​ ​

​ ​as​ ​

​ ​select​ ​​ ​ [其他的列], ​ ​

​ ​ ​ ​​ ​to_number(Char_Col) col_name​ ​

​ ​from​ ​​ ​ foo;​ ​



然后drop 原表,新表更名为原表:  ​ ​?​ ​



1 2


​ ​drop​ ​​ ​ table​ ​​ ​ foo; ​ ​

​ ​rename new ​ ​​ ​to​ ​​ ​ foo;​ ​

与方法1一样要注意新建相关对象。

3. 创建临字段替换


新建一个临时字段,把要修改的字段的内容备份到临时字段后清空原字段,然后再修改类型,之后再把临时字段的内容复制到修改后的字段,最后删除临时字段


1 2 3 4 5 6 7


​ ​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;​ ​

​
​