我有以下查询来更新[SetID]列中的随机数。
"更新员工集合SetID=CAST(RAND(CHECKSUM(NEWID((((*5作为INT(+1"更新随机数查询
但有时在执行查询后,我会在几行中得到相同的数字。我不想在那一行再重复以前的数字。提前感谢。:(
你的问题很模糊,但我没有足够的声誉让你澄清……所以我解释你想要的是将SetID设置为1到5之间的数字,并且你不想使用与UPDATE之前的行相同的数字。如果是这样的话,那么这就是我的答案:
update E SET SetID = case when SetID <> r1.R1To5 then r1.R1To5
when SetID <> r2.R1To5 then r2.R1To5
when SetID <> r3.R1To5 then r3.R1To5
when SetID <> r4.R1To5 then r4.R1To5
when SetID <> r5.R1To5 then r5.R1To5
else case when SetID = 5 then 1
else SetID +1
end
end
from Employee E
cross apply (VALUES (CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 )) r1 (R1To5)
cross apply (VALUES (CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 )) r2 (R1To5)
cross apply (VALUES (CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 )) r3 (R1To5)
cross apply (VALUES (CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 )) r4 (R1To5)
cross apply (VALUES (CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 )) r5 (R1To5)
GO