【问题标题】:Limit the insertion/deletion using a threshold value使用阈值限制插入/删除
【发布时间】:2020-02-24 21:27:21
【问题描述】:

我想在表上使用触发器来防止在 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

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

【问题讨论】:

  • 不,您不会为此使用try/catch。您将使用触发器。
  • 在您的触发器中计算inserted 表中的条目
  • 好的。谢谢你,戈登·林诺夫。但是如何通过使用触发器设置阈值假设 2 来防止批量更新或删除表中的数据条目。
  • @DaleK,您能详细说明一下吗?
  • if (select count(*) from Inserted) > 1 rollback;

标签: sql sql-server tsql


【解决方案1】:

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

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

这非常适合我的场景。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2017-10-22
    相关资源
    最近更新 更多