6

In a table I have created a new column that's going to hold a randomized alphanumeric string. I've been using the NEWID() function. From my understanding, NEWID should just create a new guid per row but all my rows end up with the same guid.

My code is:

DECLARE @random_guid
SET @random_guid = NEWID()
UPDATE this_table
SET random_column = @random_guid

Thanks in advance for any help!

Robyn Dias
  • 95
  • 1
  • 1
  • 7
  • 3
    You need a 'where' clause to restrict which rows to update. Currently it updates every row in the table. – Ryan Vincent Dec 21 '16 at 19:49
  • 1
    You are setting a _variable_ to a single value and then using that _variable_ for every row. If you called the function directly it _would_ call it for every row. – D Stanley Dec 21 '16 at 19:50
  • Currently I am using a 'where' clause to test on a handful of rows so I don't change everything but it will eventually need to change every row – Robyn Dias Dec 21 '16 at 19:51

1 Answers1

16

That's probably cause you are setting the variable first and using it. Rather directly use the function like

UPDATE this_table
SET random_column = NEWID();
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • That worked so thank you for that. But a different issue arose. I was using this as a salt for password hashing (I know guids are bad but it's the easiest way I have to suddenly give a lot of records hashed passwords). If I set my update statement like the above code, can I access what the value of random_column is set to? – Robyn Dias Dec 21 '16 at 20:11
  • @RobynDias, Yes you can ... probably you might want to post a separate question with your new issue. – Rahul Dec 21 '16 at 20:13