Skip to content
Advertisement

How can I generate a random timestamp appended to getdate() in SQL Server?

The following sql select generates the current date and time:

select
Getdate() AS DueDate

which looks like:

2021-02-06 10:16:35.340

I’d like to use getdate() (or an equivalent alternative) to continue getting the current date but I’d like to randomize the time component. I am having trouble finding a workable solution within a select statement.

Any suggestions?

Advertisement

Answer

here is another way if you need to have random time for each row:

SELECT
   DATEADD(SECOND ,RAND(CHECKSUM(NEWID())) * 86400,CONVERT(datetime,CONVERT(varchar(8),GETDATE(),112))) 
FROM tablename
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement