gpt4 book ai didi

sql-server - 如何优化运行数百万条记录的 SQL Server Merge 语句

转载 作者:行者123 更新时间:2023-12-04 00:06:19 25 4
gpt4 key购买 nike

我使用 SQL Server 2014,需要更新一个表中新添加的日期时间类型列。有两个相关的表(都有 > 3000 万条记录):

表A:

CategoryID, itemID, dataCreated, deleted, some other string properties. 

此表包含每个项目的多个记录,具有不同的 datecreated .

表B:
CategoryID, itemID, LatestUpdatedDate (This is the new added column)

两者 categoryIDitemID是该表索引的一部分。

更新 tableB 的 LatestUpdatedDate从表 A 上匹配 CategoryIDItemID ,我使用了以下合并语句:
merge [dbo].[TableB] with(HOLDLOCK) as t
using
(
select CategoryID,itemID, max(DateCreated) as LatestUpdatedDate
from dbo.TableA
where TableA.Deleted = 0
group by CategoryID,itemID
) as s on t.CategoryID = s.CategoryID and t.itemID = s.itemID

when matched then
update
set t.LatestUpdatedDate = s.LatestUpdatedDate

when not matched then
insert (CategoryID, itemID, LatestUpdatedDate)
values (s.CategoryID, s.itemID)

鉴于两个表中有数百万条记录,我该如何优化这个脚本?或者有没有其他方法可以以更好的性能更新表?

注意:这是一个一次性脚本,DB 正在运行,将来会有一个触发器添加到 tableA 以防止插入以更新 tableB 中的日期。

最佳答案

根据 Optimizing MERGE Statement Performance ,你能做的最好的是:

  • 在源表中的连接列上创建唯一且覆盖的索引。
  • 在目标表中的连接列上创建唯一的聚集索引。

  • 您可能会在 MERGE1 期间获得性能提升通过在 TableA 上创建索引在 (Deleted, CategoryID, itemID) INCLUDE(DateCreated) .但是,由于这是一次性操作,因此创建此索引所需的资源(时间、CPU、空间)可能不会抵消按原样运行查询并依赖现有索引的性能提升.

    关于sql-server - 如何优化运行数百万条记录的 SQL Server Merge 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42194584/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com