I am trying to create a user defined function which calls the system RAND()
function inside it, when I try to create the function it errors out with the following message:
Msg 443, Level 16, State 1, Procedure getNumber, Line 10
Invalid use of a side-effecting operator 'rand' within a function.
My function code:
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
How can I fix this please?
SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).
Return type of rand() function is: Explanation : return type of rand() is integer.
To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.
The problem is that you cannot call a non-deterministic function from inside a user-defined function.
I got around this limitation by creating a view, call that function inside the view and use that view inside your function, something like this......
CREATE VIEW vw_getRANDValue
AS
SELECT RAND() AS Value
ALTER 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 = (SELECT Value FROM vw_getRANDValue) * @RtnValue * (1.0000/100.0000) --<-- to make sure its not converted to int
RETURN @RtnValue;
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With