我运行此查询以使用随机数填充字段,但它会保留一些重复记录。知道如何删除重复项吗?
UPDATE APRFIL
SET ALTATH = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000);
答案 0 :(得分:1)
生成的随机值可能已存在于表中。试试这个。
UPDATE APRFIL
SET ALTATH = (SELECT ran
FROM (SELECT CONVERT(INT, Rand(Checksum(Newid())) * 10000) ran) a
WHERE NOT EXISTS (SELECT 1
FROM APRFIL Ap
WHERE ap.ALTATH = a.ran))
更新:最好删除重复的行并插入新记录。使用while循环插入所需数量的记录
Insert into APRFIL(ALTATH)
SELECT ran FROM (SELECT CONVERT(INT, Rand(Checksum(Newid())) * 10000) ran) a
WHERE NOT EXISTS (SELECT 1
FROM APRFIL Ap
WHERE ap.ALTATH = a.ran)
答案 1 :(得分:0)
您可以使用随机数生成相关数字然后 与行号上的原始表联接以选择随机数:
-- create temp table with numbers
;WITH r AS (
SELECT 1 AS n
UNION ALL
SELECT n+1 FROM r WHERE n+1<=10000
)
SELECT n, ROW_NUMBER() OVER( ORDER BY NEWID()) random INTO #tempnums FROM r
OPTION (Maxrecursion 0)
-- update
UPDATE x SET ALTATH=t.random
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY ALTATH) rown FROM APRFIL) x
JOIN #tempnums t ON t.n=x.rown