I started by reading vongrunts's excellent FAQ on random numbers. Highly recommended!
For my application, I need random integers 0 - 9 inclusive. The following code looks like it will work for me, it is lifted almost straight from vongrunt's FAQ.
A couple of things I ran into that might be of interest however. The first commented line yielded roughly twice as many 1's as I expected, and the second line never returned a zero. Solved by switching from LEFT to RIGHT and dropping the RAND function in favor of just using CHECKSUM against NEWID. But not really sure why this is so...?
I'd be curious to see other people's approaches to random numbers. TIA Mike
For my application, I need random integers 0 - 9 inclusive. The following code looks like it will work for me, it is lifted almost straight from vongrunt's FAQ.
A couple of things I ran into that might be of interest however. The first commented line yielded roughly twice as many 1's as I expected, and the second line never returned a zero. Solved by switching from LEFT to RIGHT and dropping the RAND function in favor of just using CHECKSUM against NEWID. But not really sure why this is so...?
Code:
USE SANDBOX
DECLARE @counter smallint
SET @counter = 1
DECLARE @TBLDICE TABLE (ROLLS INT)
WHILE @counter < 5000
BEGIN
-- Next line tends to yield twice as many ones (1) as expected
-- INSERT INTO @TBLDICE SELECT LEFT(1 + 10*RAND(CHECKSUM(NEWID())),1)
-- Next Line never yields zero
-- INSERT INTO @TBLDICE SELECT RIGHT(1 + 10*RAND(CHECKSUM(NEWID())),1)
INSERT INTO @TBLDICE SELECT RIGHT(CHECKSUM(NEWID()),1)
SET NOCOUNT ON
SET @counter = @counter + 1
SET NOCOUNT OFF
END
SELECT ROLLS, COUNT(ROLLS) FROM @TBLDICE GROUP BY ROLLS ORDER BY ROLLS
I'd be curious to see other people's approaches to random numbers. TIA Mike