简体   繁体   中英

Random Function behavior in SELECT query in SQL Server

I have a written a random function dbo.UDF_Q_RandomNumber() that generates a floating type random number between 0 and 1.

DECLARE @upper = 10    
DECLARE @lower = 1    

SELECT  
    ROUND(CAST((@lower + (@upper - @lower) * dbo.UDF_Q_RandomNumber()) AS INT), 0) 

The above code generates a random number between 1 and 10.

Now I created a temporary table #tempTable with 10 rows in it with columns Id and Number .

Id  Number
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10 

SQL query:

CREATE TABLE #tempTable(Id INT, Number INT)

INSERT INTO #tempTable VALUES (1,1)
INSERT INTO #tempTable VALUES (2,2)
INSERT INTO #tempTable VALUES (3,3)
INSERT INTO #tempTable VALUES (4,4)
INSERT INTO #tempTable VALUES (5,5)
INSERT INTO #tempTable VALUES (6,6)
INSERT INTO #tempTable VALUES (7,7)
INSERT INTO #tempTable VALUES (8,8)
INSERT INTO #tempTable VALUES (9,9)
INSERT INTO #tempTable VALUES (10,10)

DECLARE @maxCount INT;

SELECT @maxCount=  COUNT(1) FROM #tempTable

SELECT * FROM #tempTable

SELECT Number 
FROM #tempTable 
WHERE Id = ROUND(CAST((1+(@maxCount-1)*dbo.UDF_Q_RandomNumber())AS INT),0)
DROP TABLE #tempTable

Here the query

SELECT Number 
FROM #tempTable 
WHERE Id = ROUND(CAST((1+(@maxCount-1)*dbo.UDF_Q_RandomNumber()) AS INT), 0)

Sometimes it returns 2 rows and sometimes null which should not come as Id selected is between 1 and 10 (the rows in temptable) and every Id has value too.

Please help .

Without seeing the function, it's hard to say, but I suspect your function is non-deterministic, so it gets interpreted for each row of the table.

If you use rand() it only returns one row

 SELECT Number FROM #tempTable WHERE Id= ROUND(CAST((1+(@maxCount-1)*rand())AS INT),0)

Alternatively, if you just want a random @n rows...

 select top (@n) * from #tempTable order by newid()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM