在一个触发器中插入和删除

时间:2015-07-24 02:07:11

标签: sql sql-server tsql triggers

如何将以下两个触发器组合在一起,一个'插入后',另一个'删除'后触发到一个触发器中?

create trigger TechStaff_update_Studio
on TechStaff after insert
begin
    update Studio
    set employees = employees + 1
    where studioID = Studio.studioID
end

create trigger TechStaff_update_Studio2
on TechStaff after delete
as
begin
    update Studio
    set employees = employees - 1
    where studioID = Studio.studioID
end

3 个答案:

答案 0 :(得分:2)

像这样,我想:

create trigger TechStaff_update_Studio
on TechStaff after insert, delete
as
begin
    update s set employees = employees
        + (select count(*) from inserted)
        - (select count(*) from deleted)
    from Studio s

end

请注意,您必须实际计算行数,而不是假设每次触发器执行时插入/删除一行(例如delete * from TechStaff将触发触发器)。

请参阅the inserted and deleted pseudo-tables上的MSDN。

你的where子句总是正确的(studioID = studioID),因此不需要。我假设你的意思是更新Studio表的每一行(只有一行?)。

编辑:由于您说有多个Studio行,因此您需要更加聪明。您必须通过StudioID获取已删除和插入的行数。以下内容可能会简化,但我没有时间缩短它。

create trigger TechStaff_update_Studio
on TechStaff after insert, delete
as
begin
    update s set employees = employees + c.Delta
    from Studio s
    join (
        select StudioID, sum(i) as Delta
        from (
            select StudioID, 1 as i from inserted
            union all
            select StudioID, -1 as i from deleted 
        ) counts
        group by StudioID
    ) c on c.StudioID = s.StudioID
end

答案 1 :(得分:0)

只需你可以在一个触发器中处理它:

CREATE TRIGGER [dbo].[<TriggerName>]
ON [<SchemaName>].[<TabaleName>] FOR INSERT, DELETE
AS 
........-- Your Code

请记住,在Trigger中,您可以使用两个表DeletedInserted,它们与表的结构相同,并且它们具有插入或删除的行。

有关详细信息,请参阅此链接:Use the inserted and deleted Tables

答案 2 :(得分:0)

您可以使用“表格”来检查数据是INSERTED还是DELETED(更新被视为删除)。

在你的IF语句中使用它:

检查更新:

>>

用于检查插入内容:

SELECT * FROM DELETED 

修改

这适用于SQL Server