创建部门表和员工表
CREATE TABLE `dept` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`deptName` varchar(30) DEFAULT NULL,
`address` varchar(40) DEFAULT NULL,
`ceo` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10001 DEFAULT CHARSET=utf8
CREATE TABLE `emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`empno` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`deptId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=500001 DEFAULT CHARSET=utf8
创建函数,随机生成字符串和部门编号
CREATE DEFINER=`root`@`%` FUNCTION `rand_num`(from_num INT ,to_num INT) RETURNS int(5)
begin
declare i int default 0;
set i=FLOOR(from_num +RAND()*(to_num -from_num+1));
return i;
end
CREATE DEFINER=`root`@`%` FUNCTION `rand_string`(n int) RETURNS varchar(255) CHARSET utf8
begin
declare chars_str varchar(100) default 'qwertyuiopasdfghjklzxcvbnm';
declare return_str varchar(255) default '';
declare i int default 0;
while i<n do
set return_str=concat(return_str,substring(chars_str,floor(1+rand()*52),1));
set i=i+1;
end while;
return return_str;
end
创建存储过程
CREATE DEFINER=`root`@`%` PROCEDURE `insert_dept`(max_num int)
begin
declare i int default 0;
set autocommit=0;
repeat
set i=i+1;
insert into dept(deptname,address,ceo) values(rand_string(8),rand_string(10),rand_num(1,500000));
until i=max_num
end repeat;
commit;
end
CREATE DEFINER=`root`@`%` PROCEDURE `insert_emp`(in start int(10),in max_num int(10))
begin
declare i int default 0;
set autocommit= 0;
repeat
set i=i+1;
insert into emp(empno, NAME ,age ,deptid)
values((start+i),rand_string(6),rand_num(30,50),rand_num(1,10000));
until i=max_num
end repeat;
commit;
end
调用存储过程批量插入数据
call insert_dept(10000);
CALL insert_emp(100000,500000);