sql - 使用阈值限制插入/删除
问题描述
我想在表上使用触发器来防止在 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)等。
解决方案
我真的很抱歉造成混乱......问题中的查询非常适合我的场景。
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
这非常适合我的场景。
推荐阅读
- python - 答案创建视图没有在 django 的数据库中存储数据
- c# - 根据从控制器传递的数据在视图中显示列表
- python - 按键分组的两个元组列表中的总和值
- google-api - Google 课堂(PHP 客户端服务):创建具有截止日期但未设置截止时间的 CourseWork
- reactjs - React/Redux/Typescript - 使用嵌套列表时,TS322 的 Material-UI 错误
- python - 将数据框重组为多索引
- javascript - 打开时滚动到引导手风琴的顶部
- visual-studio - 如何关闭由 EnvDTE 启动的 Visual Studio 进程
- java - Apache Batik 无法在 Swing 应用程序中显示 SVG
- android - 如何定义 LottieDrawable?