函数:
1 | DELIMITER $$ |
2 |
3 | CREATE |
4 | FUNCTION `RandomDateTime`(sd DATETIME,ed DATETIME) |
5 | RETURNS DATETIME |
6 | BEGIN |
7 | RETURNDATE_ADD(sd,INTERVAL FLOOR(1+RAND()*((ABS(UNIX_TIMESTAMP(ed)-UNIX_TIMESTAMP(sd)))-1)) SECOND); |
8 | END$$ |
9 |
10 | DELIMITER ; |
Sql代码:
1 | DECLARE sub INT DEFAULT 0; |
2 | DECLARE ret DATETIME; |
3 |
4 | SET sub = ABS(UNIX_TIMESTAMP(ed)-UNIX_TIMESTAMP(sd)); |
5 | SET ret = DATE_ADD(sd,INTERVAL FLOOR(1+RAND()*(sub-1)) SECOND); |
测试:
1 | </pre> |
2 | SELECTRandomDateTime(DATE_FORMAT('2010-12-1 10:10:10','%Y-%m-%d %H:%i:%s'),DATE_FORMAT('2010-12-1 11:10:13','%Y-%m-%d %H:%i:%s')) ASt; |
3 | <pre> |