Friday, April 2, 2010

RANDOM NUMBER SELECTION _USING SQL SERVER 2005 CHECKSUM(NEWID())

You can use the expression:

abs(checksum(newid()))%n + 1

CHECKSUM(NEWID()) returns a random integer. Applying ABS on top
ensures you get a nonnegative integer. Applying %n (modulo n) ensures that
the value is >= 0 and < n. By adding 1 you ensure that the value is >= 1 and
<= n. In short, this is just another way to get a random integer value in the
range 1 through n. So the above query can be rewritten as follows:

select
case rnd
when 1 then 'option one'
when 2 then 'option two'
when 3 then 'option three'
else 'oops'
end
from (select abs(checksum(newid()))%3 + 1 as rnd) as d;

EX:

DECLARE @n int
SET @n = 4


SELECT
AC.ArticleCategoryId,
AC.Description,
A.ArticleId,
A.Title
FROM ArticleCategories AC (NoLock)
CROSS APPLY (
SELECT TOP(@n) ArticleId, Title
FROM Articles A (NoLock)
WHERE A.ArticleCategoryId = AC.ArticleCategoryId
ORDER BY CHECKSUM(NEWID())
) A

No comments:

Post a Comment