我有两张桌子。 Table 1
有大约80行和 Table 2
有大约1000万。
我想更新所有行 Table 2
从中随机排 Table 1
。我不希望所有行都有相同的行。是否可以更新 Table 2
并让它为它正在更新的每一行随机选择一个值?
这是我尝试过的,但它在每一行中都有相同的值。
update member_info_test
set hostessid = (SELECT TOP 1 hostessId FROM hostess_test ORDER BY NEWID())
**编辑
好吧,我认为这是我写过的最奇怪的查询之一,我认为这将是非常缓慢的。但试一试:
UPDATE A
SET A.hostessid = B.hostessId
FROM member_info_test A
CROSS APPLY (SELECT TOP 1 hostessId
FROM hostess_test
WHERE A.somecolumn = A.somecolumn
ORDER BY NEWID()) B
我认为这会起作用(至少,这个 with
部分确实):
with toupdate as (
select (select top . . . hostessId from hostess_test where mit.hostessId = mit.hostessId order by newid()) as newval,
mit.*
from member_info_test mit
)
update toupdate
set hostessid = newval;
这个(和Lamak的)的关键是子查询中的外部相关性。这说服优化器实际运行每行的查询。我不知道为什么这会起作用而另一个版本不会。
以下是我最终使用的内容:
EnvelopeInformation将是您的表2
PaymentAccountDropDown将是你的表1(在我的情况下我有3个项目) - 为你的用例改变3到80。
;WITH cteTable1 AS (
SELECT
ROW_NUMBER() OVER (ORDER BY NEWID()) AS n,
PaymentAccountDropDown_Id
FROM EnvelopeInformation
),
cteTable2 AS (
SELECT
ROW_NUMBER() OVER (ORDER BY NEWID()) AS n,
t21.Id
FROM PaymentAccountDropDown t21
)
UPDATE cteTable1
SET PaymentAccountDropDown_Id = (
SELECT Id
FROM cteTable2
WHERE (cteTable1.n % 3) + 1 = cteTable2.n
)
参考:
http://social.technet.microsoft.com/Forums/sqlserver/pt-BR/f58c3bf8-e6b7-4cf5-9466-7027164afdc0/updating-multiple-rows-with-random-values-from-another-table
使用随机字段更新表
UPDATE p
SET p.City= b.City
FROM Person p
CROSS APPLY (SELECT TOP 1 City
FROM z.CityStateZip
WHERE p.SomeKey = p.SomeKey and -- ... the magic! ↓↓↓
Id = (Select ABS(Checksum(NewID()) % (Select count(*) from z.CityStateZip)))) b