触发受影响的列

时间:2018-03-20 09:32:38

标签: sql sql-server triggers

我希望对表格中插入值的最大数量并创建触发器。

create trigger LimitTable
on [dbfastsprocess].[dbo].[fp_campaign_winner_list]
after insert
as
declare @tableCount int
select @tableCount = Count(*)
from [dbfastsprocess].[dbo].[fp_campaign_winner_list]
WHERE campaign_id = 13

if @tableCount > 1000
begin
    rollback
end
go

我尝试在campaign_id = 12时插入值,但触发器也被触发了。只有'campaign_id = 13'时我才想触发触发器 插入?

1 个答案:

答案 0 :(得分:0)

这在SQL Server中相当棘手,因为你必须处理同时插入的多行。

我认为这可以满足您的需求:

create trigger LimitTable on dbfastsprocess.dbo.fp_campaign_winner_list
after insert as
begin

    declare @tableCount int;
    select @tableCount = Count(*)
    from dbfastsprocess.dbo.fp_campaign_winner_list wl
    where wl.campaign_id = 13;

    if (@tableCount > 1000 and
        exists (select 1 from inserted i where i.campaign_id = 13)
       )
    begin
        rollback
    end;
end;
go