经常在存储过程中删除

时间:2017-03-24 13:10:37

标签: sql sql-delete

如何创建存储过程并使用频繁查询,如下所示:

    SET NOCOUNT ON;
    DECLARE @r INT;
    SET @r = 1;
    WHILE @r > 0
    BEGIN
      BEGIN TRANSACTION;
      DELETE TOP (100000)
        dbo.table1
        WHERE Create_Date < DATEADD(YEAR, -5, GETDATE());
      SET @r = @@ROWCOUNT;
      COMMIT TRANSACTION;
      CHECKPOINT;
END

在我的新存储过程中? 谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容使DELETE语句动态化:

CREATE PROCEDURE dbo.DeleteRows (
    @tableName VARCHAR(50),
    @timestampColName VARCHAR(100),
    @since DATETIME2,
    @rows INT = 100000
AS
BEGIN

    SET NOCOUNT ON;
    DECLARE @r INT;
    SET @r = 1;
    WHILE @r > 0
    BEGIN
       -- SQL injection might be a problem if table and column name are not coming from a trustworthy source (i.e. user input)
       DECLARE @SQL = N'
         DELETE TOP (' + CAST(@Count AS INT) + ')' + @tableName + '
         WHERE ' + @timestampColName + ' < @since;'

      EXEC sp_executesql @SQL, N'@since DATETIME', @since = @since

      SET @r = @@ROWCOUNT;
    END
END

可以使用this question and its answers中指示的技术之一来解决SQL注入问题。