Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update rows with a random date

Tags:

sql

sql-server

I have a simple SQL table which has a DateTime column. I would like to update all the rows (>100000 rows) with a random date. Is there a simple way to do this a SQL Query?

like image 814
Martin Avatar asked Apr 27 '09 18:04

Martin


People also ask

How do I generate a random date in SQL?

In this case ( DATEDIFF(DAY,@start,@end ), the difference between the start date and end date will be obtained in days. By adding this value to start date, you can generate random dates between the start date and end date. However, this will not return the end date ( 1980-01-05 ) as a randomly generated date.

How do I autofill a date in SQL?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.


1 Answers

Use this to generate a smalldatetime between 01 Jan 1900 and 06 Jun 2079 (not checked, SQL not installed)

DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0) 

NEWID is better then trying to use RAND: RAND does not generate different values row in a single SELECT or UPDATE (well it didn't in SQL 2000, in case behaviour has changed).

Edit: like this

UPDATE   table SET   datetimecol = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0) 

Edit: changed 65535 to 65530 and added ABS to avoid overflow at upper limit of range

like image 96
gbn Avatar answered Oct 16 '22 07:10

gbn