更新或删除时触发SQL

时间:2014-09-22 01:27:43

标签: sql-server tsql

我必须在UPDATE或DELETE操作中触发一个触发器。当某个列更新时,我的触发器工作正常。但是,当触发DELETE操作时,我需要不同的逻辑。如何在一个触发器中同时具有两个逻辑?以下是我到目前为止的情况:

ALTER TRIGGER [dbo].[Audit_Emp_Trigger]
   ON  [dbo].[EMPLOYEE]
   AFTER UPDATE, DELETE
AS 

BEGIN
    --Only execute the trigger if the Dno field was updated or deleted
    IF UPDATE(Dno)
    BEGIN

    --If the Audit_Emp_Record table does not exist already, we need to create it
    IF OBJECT_ID('dbo.Audit_Emp_Record') IS NULL
    BEGIN
    --Table does not exist in database, so create table
    CREATE TABLE Audit_Emp_Record
    (
    date_of_change smalldatetime,
    old_Lname varchar (50),
    new_Lname varchar (50),
    old_ssn int,
    new_ssn int,
    old_dno int,
    new_dno int
    );

    --Once table is created, insert the values of the update operation into the table
    INSERT INTO Audit_Emp_Record(date_of_change, old_Lname, new_Lname, old_ssn, new_ssn, old_dno, new_dno) SELECT GETDATE(), D.Lname, I.Lname, D.Ssn, I.Ssn, D.Dno, I.Dno FROM inserted I JOIN deleted D ON I.Ssn = D.Ssn

    END

    ELSE
    BEGIN
    --The table already exists, so simply insert the new values of the update operation into the table
    INSERT INTO Audit_Emp_Record(date_of_change, old_Lname, new_Lname, old_ssn, new_ssn, old_dno, new_dno) SELECT GETDATE(), D.Lname, I.Lname, D.Ssn, I.Ssn, D.Dno, I.Dno FROM inserted I JOIN deleted D ON I.Ssn = D.Ssn
    END

    END

END

1 个答案:

答案 0 :(得分:2)

您可以通过查看哪些魔术/伪表 - INSERTEDDELETED中包含数据来测试操作类型。我更喜欢使用以下内容:

DECLARE @Operation CHAR(1);

IF (EXISTS(SELECT * FROM inserted))
BEGIN

   IF (EXISTS(SELECT * FROM deleted))
   BEGIN
      -- rows in both has to be an UPDATE
      SET @Operation = 'U';
   END;
   ELSE
   BEGIN
      -- no rows in "deleted" has to be an INSERT
      SET @Operation = 'I';
   END;

END;
ELSE
BEGIN
   -- no rows in "inserted" has to be a DELETE
   SET @Operation = 'D';
END;

然后,您可以在IF语句中使用@Operation变量来执行这些操作中的一个或另一个。

类似的东西:

IF (@Operation = 'U')
BEGIN

    --Only execute the trigger if the Dno field was updated or deleted
    IF UPDATE(Dno)
    BEGIN
       {your current code here}
    END;
END;
ELSE
BEGIN
    {what to do if the operation is a DELETE goes here}
END;

从技术上讲,您不需要设置ELSE的{​​{1}}条件,但是如果您要将此代码复制/粘贴到各种触发器中或作为模板保留,那么处理它就不会有任何损害这三个条件。

另外,作为旁注,您不需要@Operation = 'I';语句的ELSE条件,也不需要IF OBJECT_ID('dbo.Audit_Emp_Record') IS NULL之后的INSERT INTO Audit_Emp_Record条件。但在CREATE TABLE之前。如果它不存在,只需执行END,然后在该测试之外执行CREATE TABLE。含义:

INSERT