在 Table 上设置触发器以限制 INSERT、DELETE、UPDATE 操作的数量
Setup a Trigger on Table to limit the number of INSERT, DELETE, UPDATE Operations
例如:用户不能执行INSERT
、DELETE
和UPDATE
操作超过X 在给定时间点在特定 table 上的次数,如果用户执行操作 X+1 次则触发启动。
create table dbo.targetTable
(
id int,
colA varchar(10)
);
go
create or alter trigger dbo.DMLxTimes on dbo.targetTable
for insert, update, delete
as
begin
/*
--old days..
IF @@ROWCOUNT > 5
begin
rollback;
end
--*/
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
rollback;
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
例如:用户不能执行INSERT
、DELETE
和UPDATE
操作超过X 在给定时间点在特定 table 上的次数,如果用户执行操作 X+1 次则触发启动。
create table dbo.targetTable
(
id int,
colA varchar(10)
);
go
create or alter trigger dbo.DMLxTimes on dbo.targetTable
for insert, update, delete
as
begin
/*
--old days..
IF @@ROWCOUNT > 5
begin
rollback;
end
--*/
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
rollback;
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