[Help-SQL]: 下次使用随机函数更新 table 列时,我不想在单元格中使用相同的数字

[Help-SQL]: i don't want the same number in cell when i am updating table column next time using Random function

我有以下查询来更新 [SetID] 列中的随机数。

" UPDATE Employee SET SetID = CAST(RAND(CHECKSUM(NEWID())) * 5 as INT) + 1 " Update Random Number query

但有时我在执行查询后在几行中得到相同的数字。我不想在该行再次重复之前的号码。提前致谢。 :)

你的问题很模棱两可,但我没有足够的声誉让你澄清它......所以我解释你想要的是将 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