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

最近做項(xiàng)目,有需求是要把項(xiàng)目從MySql轉(zhuǎn)為Oracle數(shù)據(jù)庫,于是就有了這篇文章。簡單記錄一下,以后再有需要拿來用。
首先是MySql整庫遷移到Oracle,方法比較簡單,用Navicat數(shù)據(jù)傳輸功能,可以很方便的搞定,其中只有一項(xiàng)需要注意的地方(我只遇到一個(gè)),就是Oracle限制了表名長度最大30個(gè)字節(jié),也就是說字母+數(shù)字+字符一共有30個(gè)長度,如果有個(gè)別表名超過了30字節(jié),那么需要重新取名,字段名貌似也有這個(gè)限制,不過我沒有遇到,如果遇到了,那么同樣要做縮減。同時(shí)要更改代碼中實(shí)體和字段名的對應(yīng)關(guān)系。
接下來就是Oracle另一個(gè)限制,大小寫的問題。相信很多同道和我一樣,習(xí)慣于MySql數(shù)據(jù)庫表名和字段名小寫,那么在庫遷移過程中大小寫是不會變化的,但是在Oracle中,如果表名和字段名在定義的時(shí)候是小寫的,那么SQL操作時(shí)候,表名和字段名是需要用引號括起來的,但是之前項(xiàng)目中的SQL完全沒有這么寫過,那怎么辦,改代碼嗎?我想大部分人都會選擇去改數(shù)據(jù)庫解決這個(gè)問題——把數(shù)據(jù)庫中表名和字段名都改成大寫就可以解決這個(gè)問題了。
我手動(dòng)改了兩張表之后,看著剩下的155張表陷入了沉思:不可能,這個(gè)世界上最懶的人就是程序員,程序員不可能用這樣的方法去改,趕快找好搭檔搜索引擎來一波。果然天無絕人之路。找到了幾個(gè)存儲過程,完美解決這個(gè)問題:
- 將指定表所有字段變?yōu)榇髮懀ò选氨砻碧鎿Q成要修改的表名就可以了)。
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||'已經(jīng)存在');
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;
- 批量將空間內(nèi)所有表的所有字段名變成大寫。
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||'已經(jīng)存在');
end;
end loop;
end;
end loop;
end;
- 將用戶空間的所有表名及所有字段變?yōu)榇髮憽?/li>
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||'已經(jīng)存在');
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;
相信這幾個(gè)存儲過程就足夠解決大多數(shù)問題了。