1. 创建实例
#1 建表dept CREATE TABLE dept( id int UNSIGNED PRIMARY KEY auto_increment, deptno MEDIUMINT UNSIGNED NOT null DEFAULT 0, dname VARCHAR(20) NOT null DEFAULT "", loc VARCHAR(13) NOT null DEFAULT "" ); #2 建表emp CREATE TABLE emp( id int UNSIGNED PRIMARY key auto_increment, empno MEDIUMINT UNSIGNED not null DEFAULT 0, ename VARCHAR(20) not null DEFAULT "", job VARCHAR(9) not null DEFAULT "", mgr MEDIUMINT UNSIGNED NOT null DEFAULT 0, hiredate date not null, sal DECIMAL(7,2) NOT null, comm DECIMAL(7,2) not null, deptno MEDIUMINT UNSIGNED not null DEFAULT 0 ); #设置log_bin_trust_function_creators show variables like 'log_bin_trust_function_creators'; set global log_bin_trust_function_creators=1; #永久配置 linux下 /etc/my.cnf 下mysqld加上log_bin_trust_function_creators=1
2. 创建产生随机字符串的函数
#随机产生字符串 DELIMITER $$ create function rand_string(n int) RETURNS varchar(255) BEGIN DECLARE chars_str VARCHAR(100) DEFAULT 'abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 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 $$
3. 产生随机部门编号
#产生随机部门编号 delimiter $$ CREATE FUNCTION rand_num() RETURNS int(5) BEGIN DECLARE i int DEFAULT 0; SET i = FLOOR(100+RAND()*10); RETURN i; END $$
4. 创建存储过程
#创建往emp表中插入数据的存储过程 delimiter $$ CREATE PROCEDURE insert_emp(in START int(10),in max_num int(10)) BEGIN DECLARE i int DEFAULT 0; #set autocommit = 0 把autocommit设置成0 SET autocommit = 0; REPEAT SET i = i + 1; INSERT INTO emp (empno,ename,job,mgr,hiredate,sal,comm,deptno) VALUES ((START+i), rand_string(6),'SALESMAN',0001,CURDATE(),2000,400,rand_num()); UNTIL i = max_num END REPEAT; COMMIT; END $$ #创建往dept表中插入数据的存储过程 delimiter $$ CREATE PROCEDURE insert_dept(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 dept (deptno,dname,loc) VALUES ((START+i), rand_string(10),rand_string(8)); UNTIL i = max_num END REPEAT; COMMIT; END $$
5. 调用存储过程
#dept,插入10条数据 DELIMITER ; CALL insert_dept(100,10); #emp,插入50万条数据 DELIMITER ; CALL insert_emp(100001,500000);
关注我的公众号,精彩内容不能错过