I ran this query to populate a field with random numbers but it keeps populating with some duplicate records. Any idea how I can remove the duplicates?
UPDATE APRFIL
SET ALTATH = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000);
Technology Tips and News
I ran this query to populate a field with random numbers but it keeps populating with some duplicate records. Any idea how I can remove the duplicates?
UPDATE APRFIL
SET ALTATH = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000);
Refer this link
https://web.archive.org/web/20090216200320/http://dotnet.org.za/calmyourself/archive/2007/04/13/sql-rand-trap-same-value-per-row.aspx
I agree RAND function generates same value for all the row. Since you are manipulating the data you should not get duplicates.
For example,
CREATE TABLE #Temp ( ItemDescription VARCHAR(30) NOT NULL ) INSERT INTO #Temp (ItemDescription) VALUES ('abc') INSERT INTO #Temp (ItemDescription) VALUES ('def') INSERT INTO #Temp (ItemDescription) VALUES ('ghi') INSERT INTO #Temp (ItemDescription) VALUES ('jkl') SELECT RAND() FROM #Temp SELECT CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000) FROM #Temp UPDATE #Temp SET ItemDescription = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000); select * from #Temp DROP TABLE #Temp
--Prashanth
Prasanth,
The table already exist. I only want to populate a column within the table with random non duplicate numbers.
Thanks
Prasanth,
The table already exist. I only want to populate a column within the table with random non duplicate numbers.
Thanks
RAND() function can generate duplicates in SET based approach.
You may try the below:(Please test it carefully)
UPDATE APRFIL SET ALTATH = Abs(Checksum(NewId()))
My complete test script as below:
create table APRFIL(ALTATH bigint) Go Insert into APRFIL Values(1) Go 1000 Select * From APRFIL UPDATE APRFIL SET ALTATH = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000) ;With cte as ( Select *,ROW_NUMBER()over(partition by ALTATH Order by ALTATH asc) Rn From APRFIL )Select* From cte Where rn>1 UPDATE APRFIL SET ALTATH = Abs(Checksum(NewId())) ;With cte as ( Select *,ROW_NUMBER()over(partition by ALTATH Order by ALTATH asc) Rn From APRFIL )Select* From cte Where rn>1 Select* From APRFIL Drop table APRFIL
Thank you very much.
That did it. No more duplicates....