Today, the boss told me to use stored procedures to create test data, and then I pieced together, finally can use stored procedures to create test data, the first time I discovered the charm of SQL programming. The following describes the test data creation process.
1. Prepare 2 tables (user table and dept table)
Two, prepare basic knowledge
Temporary variables, local variables, cursors, loops, nested loops, etc. are used. Please refer to the reference documents I listed at the end.
3. Prepare department table data
Fourth, the storage engine is written as follows
DELIMITER //
CREATE PROCEDURE mockDataCreate(IN dataCount INT) -- dataCount各个部门人数
BEGIN
DECLARE _deptno INT; -- 部门ID
DECLARE done INT; -- 完成标记
DECLARE initCount INT; -- 初始标记
DECLARE dept_cursor CURSOR FOR SELECT id FROM dept; -- 定义游标
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- 定义记录结束后游标触发操作
SET done = 0;
SET initCount = 1;
OPEN dept_cursor; -- 打开游标
dept_cursor_loop:LOOP -- 定义循环
FETCH dept_cursor INTO _deptno; -- 使用游标获取数据到指定局部变量
IF done = 1 THEN -- 游标走到末尾,done会自动被设置为1,此时会执行此句
LEAVE dept_cursor_loop; -- 跳出循环
END IF;
data_count_loop:LOOP -- 每个部门插入人数循环
IF initCount > dataCount THEN
LEAVE data_count_loop;
END IF;
INSERT INTO user(name, deptno) VALUES(CONCAT('用户', initCount), _deptno);
SET initCount = initCount + 1;
END LOOP;
SET initCount = 1;
END LOOP;
END //
DELIMITER ;
Inserting 6W data, the execution took about 100S, which felt very slow. I don't know if it is caused by SQL parsing and single insertion every time.
Is it very fragrant? Haha, you no longer need to write Java code to insert data, you can also create related data.
Then, before the execution, I was always worried about the execution of the stored procedure. What should I do if the termination condition is not set and the data is created all the time, so Baidu also has some statements about stopping the MYSQL thread.
show procedure status; -- 查询所有存储过程状态
show create procedure proc_name; -- 查询存储过程创建
show create function func_name; -- 查询函数创建
SHOW PROCESSLIST; -- 查询当前运行的MYSQL线程
KILL 线程ID; -- 终止ID为此ID的MYSQL线程
DROP PROCEDURE [ IF EXISTS ] <过程名> -- 删除存储过程
Reference documents:
Example of using cursor in mysql stored procedure
mysql terminates the stored procedure
Instructions for using MySQL stored procedure loop nesting
Variable definition in the stored procedure
mysql view all stored procedure queries