Random select is not always returning a single row.

Posted by Lieven on Stack Overflow See other posts from Stack Overflow or by Lieven
Published on 2010-06-14T08:16:07Z Indexed on 2010/06/14 8:22 UTC
Read the original article Hit count: 209

Filed under:
|
|
|

The intention of following (simplified) code fragment is to return one random row. Unfortunatly, when we run this fragment in the query analyzer, it returns between zero and three results.

As our input table consists of exactly 5 rows with unique ID's and as we perform a select on this table where ID equals a random number, we are stumped that there would ever be more than one row returned.

Note: among other things, we already tried casting the checksum result to an integer with no avail.

DECLARE @Table TABLE (
  ID INTEGER IDENTITY (1, 1)
  , FK1 INTEGER
)

INSERT INTO @Table
SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5

SELECT  *
FROM    @Table 
WHERE   ID = ABS(CHECKSUM(NEWID())) % 5 + 1

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server