SQL Server:特定范围内的随机日期(包括随机小时,分钟......)

时间:2014-11-02 03:23:49

标签: sql-server

我想为SQL Server更新查询创建一个随机日期。我发现很多随机日子或类似的例子,但是我找不到能够创建随机日期,小时,分钟,秒和毫秒的随机日期。

这是我用来随机创建日期的,但它总是给我00作为小时,分钟,秒和毫秒,我也不知道如何将它们随机化。

这是我的疑问:

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)

3 个答案:

答案 0 :(得分:8)

我就是这样做的:

  1. 计算from和to之间的秒数
  2. 获取零到秒数之间的随机数
  3. 将该随机数添加到FromDate
  4. 最后随机化毫秒数

  5. 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))
    

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

SELECT dateaddDATEADD(second, 
          second,  (rand()*60+1), 
            DATEADD(minute,
                    (rand()*60+1) , 
                    DATEADD(day, 
                            (rand()*365+1), 
                            DATEADD(year, 
                                    -1, 
                                    getdate()))) )