如何更新 SQL 服务器中的 4 000 000 条随机记录
How to update 4 000 000 random numbers of records in SQL Server
我总共有 1000 万行,我想用一些值更新随机记录。
我想用 Datakey = 1
更新 400 万个随机行,用 Datakey = 2
更新接下来的 400 万个随机行,用 Datakey = 3
更新最后 200 万个随机行。
我尝试学习一些功能,例如 Rand()
,我想在我的请求中使用它,但我不能。我只能使用前400万来更改它们但我想要随机记录而不是前400万。
这是我的 SQL 声明:
update top (4 000 000) [FACT_INTERNATIONAL]
set [DateKey] = 2
但我想要随机的 4 000 000 而不是顶部。我正在使用 SQL Server 2017。
您可以使用 row_number()
:
with toupdate as (
select t.*, row_number() over (order by newid()) as seqnum
from t
)
update toupdate
set datekey = (case when seqnum <= 4000000 then 1
when seqnum <= 8000000 then 2
else 3
end);
注意:更新 10,000,000 条记录是一项昂贵的操作,因此这可能会花费很多时间。创建一个新的 table 复制现有数据通常更有效。但是,您的问题与性能无关。
您可以像这样在 ORDER BY
中使用 NEWID()
:
UPDATE X
SET [DateKey] = 2
FROM (SELECT TOP (4000000) *
FROM [FACT_INTERNATIONAL] AS X
ORDER BY NEWID()) AS X
4 Million records have too much cost in update, and sql may give an error after a while. Try with fewer records in my opinion.
我总共有 1000 万行,我想用一些值更新随机记录。
我想用 Datakey = 1
更新 400 万个随机行,用 Datakey = 2
更新接下来的 400 万个随机行,用 Datakey = 3
更新最后 200 万个随机行。
我尝试学习一些功能,例如 Rand()
,我想在我的请求中使用它,但我不能。我只能使用前400万来更改它们但我想要随机记录而不是前400万。
这是我的 SQL 声明:
update top (4 000 000) [FACT_INTERNATIONAL]
set [DateKey] = 2
但我想要随机的 4 000 000 而不是顶部。我正在使用 SQL Server 2017。
您可以使用 row_number()
:
with toupdate as (
select t.*, row_number() over (order by newid()) as seqnum
from t
)
update toupdate
set datekey = (case when seqnum <= 4000000 then 1
when seqnum <= 8000000 then 2
else 3
end);
注意:更新 10,000,000 条记录是一项昂贵的操作,因此这可能会花费很多时间。创建一个新的 table 复制现有数据通常更有效。但是,您的问题与性能无关。
您可以像这样在 ORDER BY
中使用 NEWID()
:
UPDATE X
SET [DateKey] = 2
FROM (SELECT TOP (4000000) *
FROM [FACT_INTERNATIONAL] AS X
ORDER BY NEWID()) AS X
4 Million records have too much cost in update, and sql may give an error after a while. Try with fewer records in my opinion.