SQL Server 2005 trigger - how to safely determine if fired by UPDATE or DELETE?

半腔热情 提交于 2019-12-24 10:23:13

问题


I have the following code in a SQL Server 2005 trigger:

CREATE TRIGGER [myTrigger] ON [myTable]
FOR UPDATE,DELETE
AS
BEGIN

DECLARE @OperationType VARCHAR(6)
IF EXISTS(SELECT 1 FROM INSERTED)
BEGIN
    SET @OperationType='Update'
END
ELSE
BEGIN
    SET @OperationType='Delete'
END

My question: is there a situation in which @OperationType is not populated correctly? E.G.: the data in the table is changed by a bunch of UPDATE/DELETE statements, but the trigger is not fired once by every one of them?

Do you have a better way to determine if the trigger was fired by an UPDATE or DELETE statement?


回答1:


Why don't you just create two separate triggers?

CREATE TRIGGER [myUpdateTrigger] ON [myTable]
FOR UPDATE
AS
BEGIN

END

CREATE TRIGGER [myDeleteTrigger] ON [myTable]
FOR DELETE
AS
BEGIN

END



回答2:


Simple answer: No, there will not be a situation in which the trigger fails to detect correctly (except when there are no changed rows).

The trigger will be fired once for every statement, so the thing is not possible and it will work correctly, but the point is, if you really want to do different tasks for UPDATE and DELETE, you'd better use a couple triggers.



来源:https://stackoverflow.com/questions/353233/sql-server-2005-trigger-how-to-safely-determine-if-fired-by-update-or-delete

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