Advanced familiarity with Mysql, using stored procedures and functions to generate test data with a specified number of rows

Create a test table

CREATE TABLE `test_num` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `age` int DEFAULT NULL,
  `rand_num` int DEFAULT NULL,
  `big_num` bigint DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `rand_age` (`rand_num`,`age`)
) ENGINE=InnoDB AUTO_INCREMENT=56393373 DEFAULT CHARSET=utf8mb3;

Create a function that randomly generates content

generate small numbers

CREATE FUNCTION `rand_min_num`() RETURNS int
begin        
  declare min_num INT(3);
	SET min_num = floor(rand()*100);
  return min_num;    
end

generate large numbers

CREATE FUNCTION `rand_max_num`() RETURNS bigint
begin        
  declare max_num BIGINT(10);
	SET max_num = floor(rand()*100000);
  return max_num;    
end

generate random characters

CREATE FUNCTION `rand_string`(n int) RETURNS varchar(255) CHARSET utf8mb3
begin        
  declare chars_str varchar(100) 
  default "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  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()*62),1));
      set i= i+1;        
  end while;        
  return return_str;    
end

Create a stored procedure and call it to generate the specified number of rows of data

Loop n ( n为入参) times, generate different data, and insert into the database

CREATE PROCEDURE `insert_data_testnum`( IN n INT )
BEGIN
	DECLARE i INT DEFAULT 1;
	DECLARE max_num BIGINT(10);
	DECLARE rand_num BIGINT(10);
	DECLARE min_num INT(5);
	WHILE(i<= n ) DO
		SET min_num = rand_min_num();
		SET rand_num = rand_max_num();
		SET max_num = rand_max_num();
		--循环执行以下插入语句
		INSERT INTO test_num ( age, rand_num,big_num ) VALUES(min_num,rand_num,max_num);
	  SET i = i + 1;
END WHILE;
END

Since our test table fields are all numeric types, the random data we use are all random numbers.

call stored procedure

-- 插入一条测试数据
CALL insert_data_testnum(1)

insert image description here
Check the database again, it has been inserted successfully. You can try to insert tens of millions of data, test sql optimization, etc...

Guess you like

Origin blog.csdn.net/languageStudent/article/details/126285089
Recommended