zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL转Oracle遇到的问题:表名长度及大小写问题

2023-03-14 09:31:26 时间

最近做项目,有需求是要把项目从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;

相信这几个存储过程就足够解决大多数问题了。