SQL - NEWID() producing the same guid on an update query
Asked Answered
S

1

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!

Sandhurst answered 21/12, 2016 at 19:46 Comment(3)
You need a 'where' clause to restrict which rows to update. Currently it updates every row in the table.Carberry
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.Cracow
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 rowSandhurst
E
17

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();
Earthworm answered 21/12, 2016 at 19:48 Comment(2)
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?Sandhurst
@RobynDias, Yes you can ... probably you might want to post a separate question with your new issue.Earthworm

© 2022 - 2024 — McMap. All rights reserved.