1. 程式人生 > >MySQL儲存函式生成批量資料

MySQL儲存函式生成批量資料

當測試SQL效能時,需要使用儲存函式造資料

建立隨機字串,引數為字串的長度

DROP FUNCTION IF EXISTS rand_string;
delimiter $$
CREATE FUNCTION rand_string (n INT) RETURNS VARCHAR (255)
BEGIN
    DECLARE chars_str VARCHAR (100) DEFAULT 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' ;
    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$$

建立隨機數,引數為隨機數的位數

DROP FUNCTION IF EXISTS rand_num;
delimiter $$
CREATE FUNCTION rand_num (n INT
) RETURNS INT (15) BEGIN DECLARE i INT DEFAULT 1 ; DECLARE total INT DEFAULT 10 ; DECLARE random INT DEFAULT 0 ; WHILE i < n DO SET total = total * 10 ; SET i = i + 1 ; END WHILE; SET random = FLOOR(RAND() * total) ; RETURN random ; END$$

批量生成隨機資料插入表

DROP PROCEDURE
IF EXISTS student_insert_procedure;
CREATE PROCEDURE student_insert_procedure (count INT) BEGIN DECLARE n INT DEFAULT 0; DECLARE days INT;#當前日期加上的隨機天數 WHILE n < count DO SET days = rand_num (3); INSERT INTO student (`id`, `stuname`, birthday)VALUES(rand_num (5),rand_string (15),DATE_ADD(CURDATE(), INTERVAL days DAY)); SET n = n + 1; END WHILE; COMMIT; END call student_insert_procedure(10);