Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Random Generated data

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-02-28 : 08:21:13
Dan writes "Hi, What would be the best way to randomly generate data for a table. I am wanting to randomly generate a card, which has card number, card sequence. The numbers generated can not be in the database already.

Cheers
Dan"

Nazim
A custom title

1408 Posts

Posted - 2002-02-28 : 08:32:02
You can use loop thru using a Rand function, and on every random value, check if it exists in your db . if it does again reloop until you add up the desired no. of records.

HTH

--------------------------------------------------------------
Go to Top of Page

Arnold Fribble
Yak-finder General

1961 Posts

Posted - 2002-02-28 : 15:17:04
If you just need unique, fairly-random-looking numbers, and you don't have to work around any existing ones, the quickest way by far would be to use a simple linear congruential generator in an update.
Say you want to create 10000 rows:

CREATE TABLE cards (i int IDENTITY PRIMARY KEY, cardnum int NOT NULL)


-- here, numbers is just any old table with at least 10000 rows!
INSERT INTO cards SELECT TOP 10000 0 FROM numbers


DECLARE @n int
-- seed the generator
SET @n = FLOOR(RAND() * 10000)
-- set the cardnum and generate the next value
UPDATE cards SET cardnum = @n, @n = (@n*3421+1) % 10000

Knuth (as reported by my trusty copy of Sedgewick) says that ideally, the number that is 3421 in this instance should have one digit less than the modulus, should end in "21" and the next digit should be even.
You'll probably want to make @n a bigint (SQL Server 2000 only) if you're generating values much larger than 10000.


Edited by - Arnold Fribble on 02/28/2002 15:33:05
Go to Top of Page
   

- Advertisement -