views:

380

answers:

8

I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.

I know I can use a cursor, but that seems inelegant.

MS-SQL 2000,BTW

+1  A: 

You might be able to adapt something like this to load a test dataset of values, depending on what you are looking for

Mitchel Sellers
A: 

If this is a one time thing just to get data into the system I really see no issue with using a cursor as much as I hate cursors they do have their place.

Jeremy Coenen
+1  A: 

Additionally, if you are just doing this for testing or one time use I would say that an elegant solution is not really necessary.

Mitchel Sellers
+5  A: 
update MyTable Set RandomFld =  CONVERT(varchar(10), NEWID())
James Curran
With this additionUPDATE table SET field = CONVERT(varchar(10), LEFT(NEWID(), 10))
Dan Williams
Sorry, don't have SQLServer running here, so I couldn't test it.
James Curran
This assigns the same randomm value to every entry. http://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005#94951 will randomize each row, and works in SQL2000
Adam
A: 

How about this:

UPDATE TBL SET Field = LEFT( CONVERT(varchar(255), @myid),10)
Stephen Wrighton
+1  A: 

Why not use the first 10 characters of an md5 checksum of the current timestamp and a random number?

A: 

if you are in SQL Server you can use

CAST(RAND() as varchar(10))

EDIT: This will only work inside an iteration. As part of a multi-row insert it will use the same RAND() result for each row.

theo
+1  A: 

Something like (untested code):

UPDATE yourtable
SET yourfield= CHAR(32+ROUND(RAND()*95,0));

Obviously, concatenate more random characters if you want up to ten chars. It's possible that the query optimizer might set all fields to the same value; in that case, I would try

SET yourfield=LEFT(yourfield,0)+CHAR…

to trick the optimizer into recalculating each time the expression.

ΤΖΩΤΖΙΟΥ