两个给定日期之间的随机日期SQL Server 2012

时间:2016-02-01 06:03:08

标签: sql sql-server sql-server-2012

我正在尝试按照

中给出的答案之一

How to insert 1000 random dates between a given range?

并使用以下代码创建函数:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION RandomDate (@fromDate DATE, @toDate DATE) 
RETURNS DATE
AS 
BEGIN
   declare @days_between int
   declare @days_rand int

   set @days_between = datediff(day,@fromDate,@toDate)
   set @days_rand  = cast(RAND()*10000 as int)  % @days_between

   return dateadd(day, @days_rand, @fromDate)
end

当我尝试创建该函数时,出现以下错误:

  

Msg 443,Level 16,State 1,Procedure RandomDate,Line 7
  在函数中无效使用副作用运算符'rand'。

关于如何修复它的任何想法?

由于

1 个答案:

答案 0 :(得分:0)

使用rand函数

创建视图
  CREATE VIEW randomView
    AS
    SELECT RAND() randomResult
    GO

使用创建的函数中的视图。

 create function RandomDate ( @fromDate date, @toDate date) returns date AS 
BEGIN
 declare @days_between int
 declare @days_rand int

  declare @rndResult int

 select @rndResult=randomResultfrom randomView

 set @days_between = datediff(day,@fromDate,@toDate)
 set @days_rand  = cast(@rndResult*10000 as int)  % @days_between

 return dateadd( day, @days_rand, @fromDate )
end