Fill the field with Random dates from the specific range in MSSQL
I had to update the date values in the MSSQL database table for tests and demo. I needed to set random Dates from the specific range.
There's a pretty looking solution how to do it.
DECLARE @start_date DATE = '2024-01-01';
DECLARE @end_date DATE = '2025-01-31';
SELECT DATEADD(DAY, ABS(CHECKSUM(NEWID())) % (DATEDIFF(DAY, @start_date, @end_date) + 1), @start_date) AS random_date;
This query will return a random value from '2024-01-01' to '2025-01-31'.
The example of the update query for the table:
DECLARE @start_date DATE = '2024-01-01';
DECLARE @end_date DATE = '2025-01-31';
update Locations set StartOf = (SELECT DATEADD(DAY, ABS(CHECKSUM(NEWID())) % (DATEDIFF(DAY, @start_date, @end_date) + 1), @start_date) AS random_date),
EndOf = (SELECT DATEADD(DAY, ABS(CHECKSUM(NEWID())) % (DATEDIFF(DAY, @start_date, @end_date) + 1), @start_date) AS random_date)
where StartOf IS NULL
Happy coding 🙂