如何删除 SQL 2005 中的记录以检查事务日志

How to delete records in SQL 2005 keeping transaction logs in check(如何删除 SQL 2005 中的记录以检查事务日志)
本文介绍了如何删除 SQL 2005 中的记录以检查事务日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下存储过程来删除大量记录.我知道 DELETE 语句写入事务日志,删除多行会使日志增长.

I am running the following stored procedure to delete large number of records. I understand that the DELETE statement writes to the transaction log and deleting many rows will make the log grow.

我已经研究了创建表和插入记录以保留然后截断源的其他选项,这种方法对我不起作用.

I have looked into other options of creating tables and inserting records to keep and then Truncating the source, this method will not work for me.

如何使下面的存储过程更高效,同时确保事务日志不会出现不必要的增长?

CREATE PROCEDURE [dbo].[ClearLog] 
(
  @Age int = 30
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

  -- DELETE ERRORLOG
  WHILE EXISTS ( SELECT [LogId]  FROM [dbo].[Error_Log] WHERE DATEDIFF( dd, [TimeStamp], GETDATE() ) > @Age )
   BEGIN
    SET ROWCOUNT 10000
    DELETE [dbo].[Error_Log] WHERE DATEDIFF( dd, [TimeStamp], GETDATE() ) > @Age

    WAITFOR DELAY '00:00:01'
    SET ROWCOUNT 0
   END
END

推荐答案

我会这样做:

CREATE PROCEDURE [dbo].[ClearLog] (  
@Age int = 30)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @d DATETIME
        , @batch INT;
    SET @batch = 10000;
    SET @d = DATEADD( dd, -@Age, GETDATE() )
    WHILE (1=1)
    BEGIN
        DELETE TOP (@batch) [dbo].[Error_Log]  
        WHERE [Timestamp] < @d;
        IF (0 = @@ROWCOUNT)
            BREAK
    END
END

  • 使时间戳比较 SARGable
  • 在批处理开始时分离 GETDATE() 以产生一致的运行(否则它会在无限循环中阻塞,因为新记录随着旧记录被删除而老化").
  • 使用 TOP 而不是 SET ROWCOUNT(已弃用:使用 SET ROWCOUNT 不会影响下一版本 SQL Server 中的 DELETE、INSERT 和 UPDATE 语句.)
  • 检查@@ROWCOUNT 以打破循环而不是多余的 SELECT
  • 这篇关于如何删除 SQL 2005 中的记录以检查事务日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)