Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : random date in specific range (including random hours, minutes,...)

Tags:

sql-server

I would like to create a random date for a SQL Server update query. I found a lot examples for random days or something similar but I couldn't find something which creates a random date with random date, hours, minutes, seconds AND milliseconds.

This is what I use to create the date randomly but it always gives me 00 as hour, minute, seconds and milliseconds and I don't know how I can randomize them as well.

This is my query:

declare @FromDate date = GETDATE()-2
declare @ToDate date = GETDATE()-1

UPDATE ACCOUNTS
SET dateFinished=
dateadd(day, rand(checksum(newid())) * (1 + datediff(day, @FromDate, @ToDate)), @FromDate)
like image 904
kentor Avatar asked Nov 02 '14 03:11

kentor


People also ask

How do you select random values in SQL?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).


2 Answers

This is how I'd do it:

  1. Work out the number of seconds between from and to
  2. Get a random number between zero and the number of seconds
  3. Add that random number to the FromDate
  4. Finally randomise the number of milliseconds

DECLARE @FromDate DATETIME = DATEADD(DAY, -2, GETDATE())
DECLARE @ToDate   DATETIME = DATEADD(DAY, -1, GETDATE())

DECLARE @Seconds INT = DATEDIFF(SECOND, @FromDate, @ToDate)
DECLARE @Random INT = ROUND(((@Seconds-1) * RAND()), 0)
DECLARE @Milliseconds INT = ROUND((999 * RAND()), 0)

SELECT DATEADD(MILLISECOND, @Milliseconds, DATEADD(SECOND, @Random, @FromDate))
like image 50
DavidG Avatar answered Oct 07 '22 09:10

DavidG


declare @FromDate dateTIME = '2014-01-01'
declare @ToDate dateTIME = '2014-12-31'

select top 100 dateadd(day,rand(checksum(newid()))*(1+datediff(day, @FromDate, @ToDate)), @FromDate) FROM Tabled(give your table name)
like image 37
Venu chembu Avatar answered Oct 07 '22 10:10

Venu chembu