将数据库从sqlserver迁移到mysql
说明:本篇仅仅代表本人遇到的情况,不保证适用于所有的场景
1、数据迁移
使用navicat进行数据传输。首先新建一个mysql数据库,用来作为目标库,然后使用navicat的迁移工具
然后选择源库和目标库:
点击下一步:
可以看到这种方式是不能导出表和序列的。在mysql中没有序列这种说法,我们可以通过另外的方式比如函数来实现序列的效果。
2、实现序列效果
数据的迁移很简单,毕竟基本都是用的同一套标准。主要是在项目中对数据库的连接方式和xml中的sql改造。
我们可以先看一下在sqlserver中序列的使用:
可以看到在插入的时候,folderId字段使用了序列 SEQ_INFO_FOLDER 的值,使用的语句是:
select next value for SEQ_INFO_FOLDER
但是在mysql中没有序列,我们可以先在mysql数据库中创建一张表sys_sequence表(名字可以自己随便取),添加两个字段
用来模拟序列的名称和值。
然后再自定义函数:
currval():
CREATE DEFINER=`root`@`%` FUNCTION `currval`(`name` text) RETURNS decimal(10,0)
begin
declare value Integer;
set value = 0;
select seq_value into value
from sys_sequence
where seq_name = name collate utf8_general_ci;
if(value = 0) then
insert into sys_sequence values (name,1);
set value = 1;
end if;
return value;
end
nextval():
CREATE DEFINER=`root`@`%` FUNCTION `nextval`(name varchar(50) character set utf8) RETURNS int(11)
begin
declare value Integer;
set value = 0;
select seq_value into value
from sys_sequence
where name = seq_name collate utf8_general_ci;
if(value = 0 ) then
insert into sys_sequence values (name,1);
else
update sys_sequence
set seq_value = seq_value + 1
where seq_name = name collate utf8_general_ci;
end if;
return currval(name);
end
setval():
CREATE DEFINER=`root`@`%` FUNCTION `setval`(name varchar(50) character set utf8,set_value integer) RETURNS int(11)
begin
declare value Integer;
set value = 0;
select seq_value into value
from sys_sequence
where seq_name = name collate utf8_general_ci;
if(value = 0) then
insert into sys_sequence values (name,set_value);
else
update sys_sequence
set seq_value = set_value
where seq_name = name collate utf8_general_ci;
end if;
return currval(name);
end
在MySQL中的使用:
备注:
当然这种方式不是唯一的,还可以用mysql的主键自增等方式,像下图这种:
3、xml中的函数改造
首先数据库配置文件中的数据库驱动,用户名、密码以及jdbcUrl需要修改
函数:
numeric改为decimal
将
cast(ISNULL(a.SORT_NO,'0') as numeric) "sortNo"
改为
cast(ISNULL(a.SORT_NO,'0') as decimal) "sortNo"
isnull()改为ifnull()
在sqlserver中isnull可以接收两个参数,但是在mysql中isnull()只接收一个参数,如果是null就返回1,否则返回0.mysql中的ifnull()才接收两个参数,如果为null可以自定义返回值
convert()
sqlserver:
convert(datetime, concat('2021-07-07',' 23:59:59'))
mysql:(参数位置和sqlserver相反)
SELECT CONVERT("2017-08-29", datetime)
format()
sqlserver:
返回以指定的格式和可选的区域性格式化的值。 使用 FORMAT 函数将日期/时间和数字值格式化为识别区域设置的字符串。 对于一般的数据类型转换,请使用 CAST 或 CONVERT。
format(f.CREATE_TIME,'yyyy-MM-dd') "createTime",
format(f.CREATE_TIME,'yyyy-MM-dd HH:mm:ss') "createTime",
mysql
format函数在mysql中是数据内容格式化的
SELECT FORMAT(100000,2);
输出结果:
100,000.00
所以在mysql中要实现上面sqlserver中的format效果,转换日期的格式,要使用date_format()函数
date_format(f.CREATE_TIME,'%Y-%m-%d') "createTime",
date_format(f.CREATE_TIME,'%Y-%m-%d %H:%i:%s') "createTime",
string_agg()
string_agg()改为group_concat()
todo
待补充…