欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MYSQL批量插入数据-存储过程

程序员文章站 2022-05-01 19:55:55
随机生成字符串DELIMITER $$CREATE function rand_string(n INT) RETURNS VARCHAR (255)BEGIN DECLARE chars_str VARCHAR(100) DEFAULT 'abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ';DECLARE return_str VARCHAR(255) DEFAULT '';DECLARE i INT DEFAULT 0;WHI...
随机生成字符串
DELIMITER $$
CREATE function rand_string(n INT) RETURNS VARCHAR (255)
BEGIN 
	DECLARE chars_str VARCHAR(100) DEFAULT 'abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ';
	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 $$;
随机生成部门编号
DELIMITER $$
CREATE FUNCTION rand_num()
RETURNS INT(5)
BEGIN
DECLARE i INT DEFAULT 0;
SET i = FLOOR(100+RAND()*10);
RETURN i;
END $$

创建存储过程

向表emp插入数据
DELIMITER $$
CREATE PROCEDURE insert_emp(IN START INT(10),IN max_num INT(10))
BEGIN
DECLARE i INT DEFAULT 0;
#关闭sql的自动提交
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插入数据
ELIMITER $$
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 $$;

调用存储过程
通过CALL进行调用,存储过程~
MYSQL批量插入数据-存储过程
500000条数据插入执行了50s左右;

本文地址:https://blog.csdn.net/weixin_44555577/article/details/107603489

相关标签: Mysql