防止删除表的所有行

时间:2012-09-25 18:19:54

标签: sql-server-2008-r2

有没有办法防止删除表中的所有行?我知道如何使用DDL触发器来防止丢弃表或截断。我曾经没有突出显示整个命令,不使用where子句,而是删除了表中的所有行。除非存在where子句,否则我想防止再次发生这种情况。

1 个答案:

答案 0 :(得分:3)

您可以使用触发器执行此操作。

CREATE TRIGGER dbo.KeepRows
ON dbo.TableName
FOR DELETE
AS
BEGIN
  SET NOCOUNT ON;

  IF NOT EXISTS (SELECT 1 FROM dbo.TableName)
  BEGIN
    RAISERROR('Naughty developer, you tried to delete the last row!', 11, 1);
    ROLLBACK TRANSACTION;
  END
END
GO

为了避免删除然后回滚(如果表很大,这可能相当昂贵),您可以将其实现为而不是触发器,这将阻止任何工作发生(当然检查除外)。这假设列id是主键:

CREATE TRIGGER dbo.KeepRows2
ON dbo.TableName
INSTEAD OF DELETE
AS
BEGIN
  SET NOCOUNT ON;

  IF EXISTS (SELECT 1 FROM dbo.TableName WHERE id NOT IN (SELECT id FROM deleted))
  BEGIN
    DELETE dbo.TableName WHERE id IN (SELECT id FROM deleted);
  END
  -- optional:
  ELSE
  BEGIN
    RAISERROR('Nice try, you need a WHERE clause!', 11, 1);
  END
END
GO