我正在尝试按照
中给出的答案之一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'。
关于如何修复它的任何想法?
由于
答案 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