Wednesday, January 1, 2025

How do I get a random date time of the current day in an SQL server?

 In SQL Server, to generate a random DATETIME value for the current day, you can use a combination of built-in functions such as GETDATE(), DATEADD(), and RAND() to create a random time within the current day.

Here is an example query that generates a random DATETIME for the current day:

SELECT DATEADD(SECOND, 
               (ABS(CHECKSUM(NEWID())) % (60 * 60 * 24)), 
               CAST(CONVERT(VARCHAR(10), GETDATE(), 120) AS DATETIME)) AS RandomDateTime

Explanation:

  1. GETDATE() gives the current date and time.
  2. CONVERT(VARCHAR(10), GETDATE(), 120) strips off the time part, leaving only the date in yyyy-mm-dd format.
  3. CAST(... AS DATETIME) converts this date string back into a DATETIME value.
  4. NEWID() generates a random uniqueidentifier value, which is then passed to CHECKSUM() to convert it into an integer.
  5. ABS(CHECKSUM(NEWID())) % (60 * 60 * 24) ensures that the random number is within the range of seconds in a single day (60 seconds * 60 minutes * 24 hours).
  6. DATEADD(SECOND, ...) adds that random number of seconds to the midnight of the current day to get a random time on the current day.

This will return a random DATETIME within today's date.

No comments:

Post a Comment