Setup a Trigger on Table to limit the number of INSERT, DELETE, UPDATE Operations

末鹿安然 提交于 2020-04-17 21:58:18

问题


For example: A user should not be able to perform INSERT, DELETE and UPDATE operations more than X number of times on a particular table at a given point of time, if the user performs an operation X+1 times than a trigger will be launched.


回答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


来源:https://stackoverflow.com/questions/60375074/setup-a-trigger-on-table-to-limit-the-number-of-insert-delete-update-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!