sql-server – 在用户定义函数中使用RAND()

我正在尝试创建一个用户定义的函数,在其中调用系统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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...