I have the table like
ID RANDOM_ID 1 123 10 456 25 789 1 1112 55 1314 10 1516
I want the result to be like :
ID RANDOM_ID 1 123 10 456 25 789 1 123 55 1314 10 456
The same ID should have same random_ids. I’m using the update statement to generate the Random_IDs after creating the table.
CREATE TABLE [RANDOMID_TABLE]([ID] [int] NULL, [RANDOM_ID] [int] NULL) GO INSERT INTO [RANDOMID_TABLE] ([ID]) select distinct ABC_ID from RANDOMID_ABC GO ******** This is the update statement for the RANDOM_ID column in [RANDOMID_TABLE] table ************ UPDATE [RANDOMID_TABLE] SET RANDOM_ID = abs(checksum(NewId()) % 1000000)
Is there something else that I need to add to the update statement?
Please advise.
Advertisement
Answer
Why would you use update
for this? Just generate the values when you insert them:
insert into [RANDOMID_TABLE] (ID, RANDOM_ID) select ABC_ID, abs(checksum(NewId()) % 1000000) from RANDOMID_ABC group by ABC_ID;
EDIT:
If your problem is collisions, then fix how you do the assignment. Just assign a number . . . randomly:
insert into [RANDOMID_TABLE] (ID, RANDOM_ID) select ABC_ID, row_number() over (order by newid()) from RANDOMID_ABC group by ABC_ID;
This is guaranteed to not return duplicates.