Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RAND() in User Defined Function

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?

like image 707
Jack Jones Avatar asked Jul 17 '15 05:07

Jack Jones


People also ask

What does RAND () in SQL do?

SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

What is the return type of rand () function?

Return type of rand() function is: Explanation : return type of rand() is integer.

How do I insert a random number in a table in SQL?

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.


1 Answers

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......

View Definition

CREATE VIEW vw_getRANDValue
AS
SELECT RAND() AS Value

Function Definition

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
like image 92
M.Ali Avatar answered Oct 11 '22 01:10

M.Ali