如何通过Loop删除多个表的数据

时间:2014-02-05 16:13:28

标签: sql sql-server tsql

我写过循环来删除表格中的数据并打印出来

SET NOCOUNT ON

DECLARE @Count INT = 1

WHILE @Count <> 0
BEGIN
      SET ROWCOUNT 100000

      DELETE
      FROM table1  

      SET ROWCOUNT 0

      SELECT @Count = COUNT(1)
      FROM table1  WITH (NOLOCK)

      --print '10000 Deleted'
      --Print cast (@count as varchar) + ' Remaining'
      DECLARE @Msg VARCHAR(100) = CAST(@Count AS VARCHAR) + ' Remaining'

      RAISERROR (
                  @Msg
                  , 0
                  , 1
                  )
      WITH NOWAIT
END

如果我想一次性使用10张桌子

select * from Sysobjects where type = 'U' and name IN ('Table1,Table2',....)

我如何在循环中实现语句逐个删除数据表数据。

2 个答案:

答案 0 :(得分:0)

你可以这样做(见下文)。这不完全是你上面所做的,但你明白了......

    SELECT id INTO #Processed FROM Sysobjects WHERE name = '(no such table)'

    DECLARE @TableId int, @TableName varchar(255), @DeletionSQL varchar(255)

    SELECT @TableId = MIN(id) FROM Sysobjects WHERE type = 'U' AND name IN ('DimAccount', 'DimCurrency', 'DimCustomer')
    AND id NOT IN (SELECT id FROM #Processed)

    SET @TableId = ISNULL(@TableId, -1)

    WHILE @TableId > -1 BEGIN

        PRINT @TableId

        SELECT @TableName = name FROM Sysobjects WHERE type = 'U' AND id = @TableId
        SET @DeletionSQL = 'DELETE FROM ' + @TableName

        PRINT @DeletionSQL
        EXEC(@DeletionSQL)


        INSERT INTO #Processed (id) VALUES(@TableId)

        SELECT @TableId = MIN(id) FROM Sysobjects WHERE type = 'U' AND name IN ('DimAccount', 'DimCurrency', 'DimCustomer')
            AND id NOT IN (SELECT id FROM #Processed)

    END

答案 1 :(得分:-3)

查看我关于删除大数据的博客文章。它提供了几种模式。

http://craftydba.com/?p=3079

我建议你选一个。您可以将代码转换为动态SQL。

但是,我会为每个表编写一个过程并将其打包在一个作业中。

一步,一桌。

这样,您可以在任何步骤重新启动作业。

注意日志文件的增长!这些细节再次出现在博客文章中。