我正在尝试创建一个用户定义的函数,在其中调用系统RAND()函数,当我尝试使用以下消息创建它错误的函数时:
Msg 443,Level 16,State 1,Procedure getNumber,Line 10
Invalid use of a side-effecting operator ‘rand’ within a function.
CREATE FUNCTION getNumber(@_id int) RETURNS DECIMAL(18,4) AS BEGIN DECLARE @RtnValue DECIMAL(18,4); SELECT TOP 1 @RtnValue = EmployeeID FROM dbo.Employees ORDER BY EmployeeID DESC SET @RtnValue = RAND() * @RtnValue * (1/100) RETURN @RtnValue; END
我该如何解决这个问题?
解决方法
问题是您无法从用户定义的函数内部调用非确定性函数.
我通过创建一个视图来解决这个限制,在视图中调用该函数并在函数中使用该视图,类似这样……
查看定义
CREATE VIEW vw_getRANDValue AS SELECT RAND() AS Value
功能定义
ALTER FUNCTION getNumber(@_id int ) RETURNS DECIMAL(18,4); SELECT TOP 1 @RtnValue = EmployeeID FROM dbo.Employees ORDER BY EmployeeID DESC SET @RtnValue = (SELECT Value FROM vw_getRANDValue) * @RtnValue * (1.0000/100.0000) --<-- to make sure its not converted to int RETURN @RtnValue; END