Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAND not different for every row in T-SQL UPDATE

I have the follow T-SQL to update a table with test data:

UPDATE
SomeTable
SET
    Created = GETDATE ( ) - CAST ( RAND ( ) * 365 AS int ) ,
    LastUpdated = GETDATE ( ) - CAST ( RAND ( ) * 365 AS int )

I want it to pick random daes in the past year, unfortunately it uses the same date for every row. what is the best way to get it to be random every row it updates?

like image 978
Keith Adler Avatar asked Jul 31 '09 20:07

Keith Adler


People also ask

How do I change the value of all rows in SQL?

Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.

Which clause is used to limit the rows to be changed in an UPDATE statement?

The LIMIT clause places a limit on the number of rows that can be updated. For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions.

How do you UPDATE more than one row?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);

Does SQL update create new row?

An UPDATE statement affects rows that already exist in the table. To add a new row to a table, you'd use an INSERT statement. (Note that the UPDATE statement in the question will update every row in the table; there isn't any WHERE clause.)


2 Answers

Use RAND(CHECKSUM(NEWID()))

  • NEWID returns a GUID
  • CHECKSUM makes it int, randomly
  • The int seeds the RAND

In your case, you could modulo the checkum because CHECKSUM(NEWID()) is already random.

CHECKSUM(NEWID()) % 365 
like image 171
gbn Avatar answered Sep 23 '22 02:09

gbn


if you only want days from the past year use this (based on @gbn's answer):

select GETDATE ( ) - ABS( CHECKSUM(NEWID()) % 365 ) 
like image 24
KM. Avatar answered Sep 23 '22 02:09

KM.