批量删除数据行

2021-09-10 00:00:00 sql tsql sql-server

我是新手,所以请保持温和.我需要删除两个表中的数百万行数据.当我使用 sql 脚本尝试此操作时,日志文件变得如此之大,以至于占用了所有硬盘驱动器并且没有完成.我在网上看了几篇文章说,如果批量删除数据,日志文件不会受到同样的影响.数据库当前处于简单模式并始终保持这种状态.这是我用来删除数据的脚本.

I'm new to this so please be gentle. I need to delete millions of rows of data in two tables. When I tried this with a sql script,the log file got so big that it took up all of hard drive and did not complete. I was reading a few articles online that said, if the data was deleted in batches that the log file would not be affected in the same way. The database in currently in simple mode and is always kept that way. this is the script I use to delete the data.

Delete from EligibilityInformation Where DateEntered <= DateAdd(day,-31, getdate())
Delete from EligibilityRequestLog Where ActualPostingDate <= DateAdd(day,-31, getdate())

有人可以帮我编写一个脚本,我可以将其添加为 SQL 作业,该脚本将一次删除 10,000 行数据,直到所有行都被删除吗?我在网上找到了以下脚本.它可能比我需要的更多.我向其中添加了我的 SQL 脚本.

Can someone help me with a script that I can add as a SQL Job that will delete 10,000 rows of data at a time until all the rows have been deleted?I found the following script online. It may be more than I need. I added my SQL script to it.

DECLARE @continue INT
DECLARE @rowcount INT

SET @continue = 1
WHILE @continue = 1
BEGIN
    PRINT GETDATE()
    SET ROWCOUNT 10000
    BEGIN TRANSACTION
    Delete from EligibilityInformation Where DateEntered <= DateAdd(day,-31, getdate())
    Delete from EligibilityRequestLog Where ActualPostingDate <= DateAdd(day,-31, getdate())
    SET @rowcount = @@rowcount 
    COMMIT
    PRINT GETDATE()
    IF @rowcount = 0
    BEGIN
        SET @continue = 0
    END
END

推荐答案

WHILE EXISTS(SELECT * FROM EligibilityInformation WHERE DateEntered <= DATEADD(DAY, -31, GETDATE()))
BEGIN
    PRINT GETDATE()
    DELETE (TOP 10000) FROM EligibilityInformation WHERE DateEntered <= DATEADD(DAY, -31, GETDATE())
    PRINT GETDATE()
END

WHILE EXISTS(SELECT * FROM EligibilityRequestLog WHERE ActualPostingDate <= DATEADD(DAY, -31, GETDATE()))
BEGIN
    PRINT GETDATE()
    DELETE (TOP 10000) FROM EligibilityRequestLog WHERE ActualPostingDate <= DATEADD(DAY, -31, GETDATE())
    PRINT GETDATE()
END

相关文章