CREATE DEFINER=`root`@`%` FUNCTION `rand_string`(n INT) RETURNSvarchar(255) CHARSET utf8mb4 DETERMINISTIC BEGIN DECLARE chars_str varchar(100) DEFAULT'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; DECLARE return_str varchar(255) DEFAULT'' ; DECLARE i INTDEFAULT0; 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
创建插入数据存储过程
1 2 3 4 5 6 7 8
CREATE DEFINER=`root`@`%` PROCEDURE `add_vote_memory`(IN n int) BEGIN DECLARE i INTDEFAULT1; WHILE (i <= n) DO INSERTINTO vote_record_memory (user_id, vote_id, group_id, create_time) VALUES (rand_string(20), FLOOR(RAND() *1000), FLOOR(RAND() *100), NOW()); SET i = i +1; END WHILE; END
CREATE DEFINER=`root`@`%` FUNCTION `rand_datetime`(sd DATETIME,ed DATETIME) RETURNS datetime DETERMINISTIC BEGIN DECLARE sub INTDEFAULT0; DECLARE ret DATETIME; SET sub =ABS(UNIX_TIMESTAMP(ed)-UNIX_TIMESTAMP(sd)); SET ret = DATE_ADD(sd,INTERVALFLOOR(1+RAND()*(sub-1)) SECOND); RETURN ret; END
-- 测试 SELECT rand_datetime(DATE_FORMAT('2017-1-1 00:00:00','%Y-%m-%d %H:%i:%s'),DATE_FORMAT('2017-12-31 23:59:59','%Y-%m-%d %H:%i:%s')) AS t;