SQL - 确定触发器中操作类型的最佳方法?

时间:2014-04-18 17:08:43

标签: sql tsql triggers sql-server-2012

下面是我用来确定插入/更新/删除操作的代码。这个问题是两部分。

一 - 这是确定操作类型的正确方法。 二 - 这是确定操作类型的最佳方法。

BEGIN
   DECLARE @ActionType   CHAR (1)

   IF NOT EXISTS (SELECT * FROM deleted) AND EXISTS (SELECT * FROM inserted)
      BEGIN
         SET @ActionType = 'I'
      END

   IF EXISTS (SELECT * FROM deleted) AND EXISTS (SELECT * FROM inserted)
      BEGIN
         SET @ActionType = 'U'
      END

   IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
      BEGIN
         SET @ActionType = 'D'
      END

      Select @ActionType;
End

1 个答案:

答案 0 :(得分:3)

一:是的。二:你可以比这更简洁。

这是我目前使用的代码。

SELECT @Action = CASE 
            WHEN EXISTS(SELECT 1 FROM INSERTED) 
             AND EXISTS(SELECT 1 FROM DELETED) THEN 'U'
            WHEN EXISTS(SELECT 1 FROM INSERTED) THEN 'I'
            ELSE 'D' END;