Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql update random between two dates

I've tried to update my database and changing dates. I've done some research but I did not found any issue. So I used two timestamp.

I've tried to do that method:

UPDATE `ps_blog_post` 
SET `time_add` = ROUND((RAND() * (1387888821-1357562421)+1357562421))

Now everywhere the new date is:

0000:00:00

Anykind of help will be much appreciated

like image 800
Stanislas Piotrowski Avatar asked Dec 25 '13 18:12

Stanislas Piotrowski


People also ask

How to generate date in SQL?

To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 .


2 Answers

Try this one to get timestamp between two timestamps

SET @MIN = '2013-01-07 00:00:00';
SET @MAX = '2013-12-24 00:00:00';

UPDATE `ps_blog_post` 
SET `time_add` =  TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN);

Fiddle

like image 60
M Khalid Junaid Avatar answered Sep 28 '22 13:09

M Khalid Junaid


You have the right idea, your conversion from the int literals you're using back to the timestamp seems off though - you're missing an explicit call to FROM_UNIXTIME:

UPDATE `ps_blog_post` 
SET `time_add` = 
     FROM_UNIXTIME(ROUND((RAND() * (1387888821 - 1357562421) + 1357562421)))
like image 28
Mureinik Avatar answered Sep 28 '22 14:09

Mureinik