Oracle限制了表名長度最大30個字節,也就是說字母+數字+字符一共有30個長度,如果有個別表名超過了30字節,那么需要重新取名,字段名貌似也有這個限制,不過我沒有遇到,如果遇到了,那么同樣要做縮減。

最近做項目,有需求是要把項目從MySql轉為Oracle數據庫,于是就有了這篇文章。簡單記錄一下,以后再有需要拿來用。
首先是MySql整庫遷移到Oracle,方法比較簡單,用Navicat數據傳輸功能,可以很方便的搞定,其中只有一項需要注意的地方(我只遇到一個),就是Oracle限制了表名長度最大30個字節,也就是說字母+數字+字符一共有30個長度,如果有個別表名超過了30字節,那么需要重新取名,字段名貌似也有這個限制,不過我沒有遇到,如果遇到了,那么同樣要做縮減。同時要更改代碼中實體和字段名的對應關系。
接下來就是Oracle另一個限制,大小寫的問題。相信很多同道和我一樣,習慣于MySql數據庫表名和字段名小寫,那么在庫遷移過程中大小寫是不會變化的,但是在Oracle中,如果表名和字段名在定義的時候是小寫的,那么SQL操作時候,表名和字段名是需要用引號括起來的,但是之前項目中的SQL完全沒有這么寫過,那怎么辦,改代碼嗎?我想大部分人都會選擇去改數據庫解決這個問題——把數據庫中表名和字段名都改成大寫就可以解決這個問題了。
我手動改了兩張表之后,看著剩下的155張表陷入了沉思:不可能,這個世界上最懶的人就是程序員,程序員不可能用這樣的方法去改,趕快找好搭檔搜索引擎來一波。果然天無絕人之路。找到了幾個存儲過程,完美解決這個問題:
- 將指定表所有字段變為大寫(把“表名”替換成要修改的表名就可以了)。
begin
for c in (select COLUMN_NAME cn from all_tab_columns where table_name='表名') loop
begin
execute immediate 'alter table 表名 rename column "'||c.cn||'" to '||c.cn;
exception
when others then
dbms_output.put_line('表名'||'.'||c.cn||'已經存在');
end;
end loop;
end;
begin
for c in (select table_name tn from user_tables where table_name <> upper(table_name)) loop
begin
execute immediate 'alter table "'||c.tn||'" rename to '||c.tn;
exception
when others then
dbms_output.put_line(c.tn||'已存在');
end;
end loop;
end;
begin
for t in (select table_name tn from user_tables) loop
begin
for c in (select column_name cn from user_tab_columns where table_name=t.tn) loop
begin
execute immediate 'alter table "'||t.tn||'" rename column "'||c.cn||'" to '||c.cn;
exception
when others then
dbms_output.put_line(t.tn||'.'||c.cn||'已經存在');
end;
end loop;
end;
end loop;
end;
begin
for t in (select table_name tn from user_tables where table_name <> upper(table_name)) loop
begin
for c in (select column_name cn from user_tab_columns where table_name=t.tn) loop
begin
execute immediate 'alter table "'||t.tn||'" rename column "'||c.cn||'" to '||c.cn;
exception
when others then
dbms_output.put_line(t.tn||'.'||c.cn||'已經存在');
end;
end loop;
execute immediate 'alter table "'||t.tn||'" rename to '||t.tn;
exception
when others then
dbms_output.put_line(t.tn||'已存在');
end;
end loop;
end;
相信這幾個存儲過程就足夠解決大多數問題了。