select
t.id,
g.id as gebruikerid
from
(
select id,
(row_number() over (order by newid())
% (select count(*) from gebruiker))+1 as rn -- number from 1 to n
from topic
) as t
join
( select id,
row_number() over (order by newid()) as rn -- sequential number from 1 to n
from gebruiker
) as g
on t.rn = g.rn
order by t.id
update t
set gebruikerid = dt.gebruikerid
from topic as t
join
(
select
t.id,
g.id as gebruikerid
from
(
select id,
(row_number() over (order by newid()) % (select count(*) from gebruiker))+1 as rn
from topic
) as t
join
( select id,
row_number() over (order by newid()) as rn
from gebruiker
) as g
on t.rn = g.rn
) as dt
on t.id = dt.id;
SELECT
t.id
,g.id AS gebruikerid
FROM
(
SELECT
id
,
(
(ROW_NUMBER() OVER (ORDER BY NEWID() ) -1)
%
(SELECT COUNT(*) FROM gebruiker)
) + 1 AS rn -- number FROM 1 to n
FROM topic
) AS t
INNER JOIN
(
SELECT
id
,ROW_NUMBER() OVER (ORDER BY NEWID() ) AS rn -- sequential number FROM 1 to n
FROM gebruiker
) AS g
ON t.rn = g.rn
ORDER BY t.id
然后,您可以使用 CTE 进行更新:
;WITH CTE AS
(
SELECT
t.id
,t.GebruikerID
,g.id AS gebruikerid
FROM
(
SELECT
id
,GebruikerID
,
(
(ROW_NUMBER() OVER (ORDER BY NEWID() ) -1)
%
(SELECT COUNT(*) FROM gebruiker)
) + 1 AS rn -- number FROM 1 to n
FROM topic
) AS t
INNER JOIN
(
SELECT
id
,ROW_NUMBER() OVER (ORDER BY NEWID() ) AS rn -- sequential number FROM 1 to n
FROM gebruiker
) AS g
ON t.rn = g.rn
)
-- SELECT * FROM CTE
UPDATE CTE SET GebruikerID = gebruikerid
ROW_NUMBER
您可以根据随机排序分配两个s 并加入它们:见小提琴
编辑:
您可以使用此 SELECT 的结果来更新
Topic
表:小提琴
死灵术。如果主题只有一个条目,并且 gebruiker 只有一个条目,则接受的答案将失败。
您需要从 row_number 中减去 -1:
然后,您可以使用 CTE 进行更新: