SQL Delete语句执行时间太长

问题描述 投票:0回答:3

我有以下SQL删除语句。这应该删除大约20000条记录,执行时间超过12分钟。在这里,我使用行号语句根据某些条件获取重复项。任何想法修改脚本以更好地执行它。提前致谢。

delete from @TempTable where id in(
        select  id
        from 
        (select ROW_NUMBER() over(partition by  Dep,  NrInvoiceLine, OfficeId, pol,  pod,  PreCarr, WarehouseId, DestinationPrecarr,
         DestinationWarehouseId, PortTerminalId, Product, isnull(description, ''), ScaleCalcuationId, isnull(scalefrom, 0), isnull(scaleto, 0),  
         CurrencyCode, Base, ShippingLineID, ContainerId, AgentId order by type) Record, a.id
        from  @TempTable a where cast(Date as smalldatetime) = '2078-12-31 00:00:00' and IsDeleted = 0 and 
        (RO = 1 or RO=2) and (PP = 0 or PP = 2) 
        )as b   
        where b.Record !=1 )
sql sql-server sql-delete query-performance
3个回答
1
投票

使用#temp表而不是表变量并创建以下索引

CREATE NONCLUSTERED INDEX NIX_temp
  ON #temptable (Date, IsDeleted, RO, PP)
  include (id, Dep, NrInvoiceLine, OfficeId, pol, pod, PreCarr, WarehouseId, DestinationPrecarr, DestinationWarehouseId, PortTerminalId, Product, description, ScaleCalcuationId, scalefrom, scaleto, CurrencyCode, Base, ShippingLineID, ContainerId, AgentId);

并尝试像这样更改查询

;WITH cte
     AS (SELECT Row_number()
                  OVER(
                    partition BY Dep, NrInvoiceLine, OfficeId, pol, pod, PreCarr, WarehouseId, DestinationPrecarr, DestinationWarehouseId, PortTerminalId, Product, Isnull(description, ''), ScaleCalcuationId, Isnull(scalefrom, 0), Isnull(scaleto, 0), CurrencyCode, Base, ShippingLineID, ContainerId, AgentId
                    ORDER BY type) Record,
                a.id
         FROM   #temptable a
         WHERE  Date >= '2078-12-31 00:00:00'
                AND Date < Dateadd(dd, 1, '2078-12-31 00:00:00')
                AND IsDeleted = 0
                AND ( RO = 1
                       OR RO = 2 )
                AND ( PP = 0
                       OR PP = 2 ))
DELETE FROM cte
WHERE  Record > 1 

0
投票

在我看来,你需要将查询分解为更小的块。这是你正在进行的高分区。

有没有更简单的方法来实现您想要的输出?您是否需要从此表中删除,或者您是否可以创建另一个只包含您想要的行,然后删除包含您不感兴趣的行的表?结果相同的方法不同。

值得注意的是,创建表的效果大多优于插入和删除行。

编辑:我可以看到你正试图减轻已经返回的副本。 99%的时间这是清理错误编码的一种方法。找出引入副本的原因,并采取正确修复数据集所需的相关步骤。


0
投票

可能导致性能不佳的主要原因是因为表变量无法获得准确的行估计值,除非您使用OPTION (RECOMPILE)。因此,您可能会根据估计表变量包含的行数远少于实际行数而获得计划。

这里也没有子查询。

你应该发现这个执行得更快。

WITH CTE
     AS (SELECT ROW_NUMBER() OVER(partition BY Dep, NrInvoiceLine, OfficeId, pol, pod, PreCarr, WarehouseId, DestinationPrecarr, DestinationWarehouseId, PortTerminalId, Product, isnull(description, ''), ScaleCalcuationId, isnull(scalefrom, 0), isnull(scaleto, 0), CurrencyCode, Base, ShippingLineID, ContainerId, AgentId ORDER BY type) Record,
                a.id
         FROM   @TempTable a
         WHERE  cast(Date AS SMALLDATETIME) = '2078-12-31 00:00:00'
                AND IsDeleted = 0
                AND ( RO IN ( 1, 2 ) )
                AND ( PP IN ( 0, 2 ) ))
DELETE FROM CTE
WHERE  Record > 1 
OPTION (RECOMPILE)
© www.soinside.com 2019 - 2024. All rights reserved.