• Shaarli
  • Tag cloud
  • Picture wall
  • Daily
  • RSS
  • Login
4252 shaares
Filters

Random Date Generator in SQL Server

QRCode

In this article we look at how to generate random dates in SQL Server to build a sample dataset along with code and examples.

SELECT DATEADD(DAY, RAND(CHECKSUM(NEWID()))*(1+DATEDIFF(DAY, @StartDate, @EndDate)),@StartDate) AS 'SalesDate';

CHECKSUM(NEWID()) is the salt for the rand() function

NEWID() generates a random unique ID for a row. Ordering by NEWID() will randomly order query results. Adding a TOP statement will return a finite number of random rows. For example, to get 10 random rows from a table:

SELECT TOP 10 * 
FROM tablename 
WHERE condition
ORDER BY NEWID()
https://www.mssqltips.com/sqlservertip/7296/random-date-generator-sql-server/#comments
July 18, 2022 at 10:10:09 AM EDT *
sql mssql
FILLER
Shaarli · The personal, minimalist, super fast, database-free, bookmarking service by the Shaarli community · Documentation
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super fast, database-free, bookmarking service by the Shaarli community