批量删除格式正确?

时间:2017-01-24 18:26:33

标签: sql sql-server tsql

我有多个表,其中有数百万行。为了安全而不是溢出事务日志,我一次批量删除它们100,000行。我必须先根据日期过滤掉,然后删除少于特定日期的所有行。

为此,我在我的存储过程中创建一个表,其中包含需要删除的行的ID:

然后我插入到该表中并使用循环从所需表中删除行。这似乎成功运行但速度极慢。这是正确的吗?这是最快的方法吗?

DECLARE @FILL_ID_TABLE TABLE (
  FILL_ID varchar(16)
)

DECLARE @TODAYS_DATE date
SELECT
  @TODAYS_DATE = GETDATE()

--This deletes all data older than 2 weeks ago from today 
DECLARE @_DATE date
SET @_DATE = DATEADD(WEEK, -2, @TODAYS_DATE)

DECLARE @BatchSize int
SELECT
  @BatchSize = 100000


BEGIN TRAN FUTURE_TRAN
  BEGIN TRY

    INSERT INTO @FILL_ID_TABLE
      SELECT DISTINCT
        ID
      FROM dbo.ID_TABLE
      WHERE CREATED < @_DATE

    SELECT
      @BatchSize = 100000
    WHILE @BatchSize <> 0
    BEGIN
      DELETE TOP (@BatchSize) FROM TABLE1
      OUTPUT DELETED.* INTO dbo.TABLE1_ARCHIVE
      WHERE ID IN (SELECT
          ROLLUP_ID
        FROM @FILL_ID_TABLE)
      SET @BatchSize = @@rowcount
    END

    SELECT
      @BatchSize = 100000
    WHILE @BatchSize <> 0
    BEGIN
      DELETE TOP (@BatchSize) FROM TABLE2
      OUTPUT DELETED.* INTO dbo.TABLE2_ARCHIVE
      WHERE ID IN (SELECT
          FILL_ID
        FROM @FILL_ID_TABLE)
      SET @BatchSize = @@rowcount
    END

    PRINT 'Succeed'
  COMMIT TRANSACTION FUTURE_TRAN
END TRY
BEGIN CATCH
  PRINT 'Failed'
  ROLLBACK TRANSACTION FUTURE_TRAN
END CATCH

1 个答案:

答案 0 :(得分:2)

尝试加入而不是子查询

DELETE  TOP (@BatchSize) T1 
OUTPUT DELETED.* INTO dbo.TABLE1_ARCHIVE
FROM  TABLE1 AS T1
JOIN @FILL_ID_TABLE AS FIL ON FIL.ROLLUP_ID = T1.Id