首页 > 解决方案 > 使用阈值限制插入/删除

问题描述

我想在表上使用触发器来防止在 count > 2 之后插入、更新或删除任何表条目。基本上我想防止使用批量操作。请问有人可以帮我吗?我们可以为此使用 try catch 吗?请找到以下用于创建触发器的命令:

create  trigger [dbo].[DMLxTimes] on [dbo].[targetTable]
for insert, update, delete
as
begin

declare @maxrows int = 5; --maximum number of rows allowed per dml action

if 
(select count(*) from inserted) > @maxrows
or
(select count(*) from deleted) > @maxrows

begin
        THROW 50005, N'This statement cannot be executed', 1;
end
end
GO

以下是尝试过的查询:

insert into dbo.targetTable(id, colA)
values (0, 'a'),(0, 'a'),(0, 'a'),(0, 'a'),(0, 'a'); --5 rows inserted
go

insert into dbo.targetTable(id, colA)
values (0, 'a'),(0, 'a'),(0, 'a'),(0, 'a'),(0, 'a'),(0, 'a'); --6 rows 
inserted ... error
go

insert into dbo.targetTable(id, colA)
values (0, 'a'),(0, 'a'); --2 rows inserted
go

--all updated, error
update dbo.targetTable
set colA = colA;
go

--ok
update top(5) dbo.targetTable
set colA = colA;
go

delete top (4) from dbo.targetTable;
go

--ok
update top(15) dbo.targetTable
set colA = colA;
go

上面的查询每次都会为插入查询提供预期的输出,但是对于不同的场景,例如当计数在当时发生变化以进行更新和删除时,查询有时会给出输出,有时对于相同的查询不会以相同的方式工作。例如,当更新顶部(14),更新顶部(20)等。

标签: sqlsql-servertsql

解决方案


我真的很抱歉造成混乱......问题中的查询非常适合我的场景。

create  trigger [dbo].[DMLxTimes] on [dbo].[targetTable]
for insert, update, delete
as
begin

declare @maxrows int = 2; --maximum number of rows allowed per dml action

if 
(select count(*) from inserted) > @maxrows
or
(select count(*) from deleted) > @maxrows

begin
        THROW 50005, N'This statement cannot be executed', 1;
end
end
GO

这非常适合我的场景。


推荐阅读