如何在 SQL 服务器中编写更新后触发器以查看以下结果

How can I write an After Update Trigger in SQL Server to see the following results

每当向 table 发送更新命令时,触发器应该只更新一条记录。

例如:table dbo.EmployeeFacts:

UPDATE EmployeeFacts
SET FactNo = 4
WHERE FactNo = 5

触发触发器时更新的必要列是:-

  1. edit_status = edit_status + 1
  2. lastupdate应该是table更新的日期
  3. UPDBYdbo
  4. 其余列将保持原样

Screenshot of result

像这样尝试,您应该在 where 子句过滤器中使用 factno(根据我的假设,它是一个主键列)您不应该更新 factno 列,因为它是一个主键。

CREATE TABLE EmployeeFacts (
    factno INT
    ,empno INT
    ,fact VARCHAR(100)
    ,createdate DATETIME
    ,editstatus INT
    ,lastupdate DATETIME
    ,updby VARCHAR(50)
    )

INSERT INTO EmployeeFacts (
    factno
    ,empno
    ,fact
    ,createdate
    )
VALUES (
    1
    ,1001
    ,'1001A'
    ,getdate()
    )
    ,(
    2
    ,1002
    ,'1002A'
    ,getdate()
    )
    ,(
    3
    ,1003
    ,'1003A'
    ,getdate()
    )
    ,(
    4
    ,1004
    ,'1004A'
    ,getdate()
    )
    ,(
    5
    ,1005
    ,'1005A'
    ,getdate()
    )

SELECT *
FROM EmployeeFacts

CREATE TRIGGER Tr_EmployeeFacts_Upd ON EmployeeFacts
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE e
    SET e.editstatus = isnull(i.editstatus, 0) + 1
        ,e.lastupdate = getdate()
        ,UPDBY = 'dbo'
    FROM EmployeeFacts e
    INNER JOIN inserted i ON e.FactNo = i.FactNo
END
GO

UPDATE EmployeeFacts
SET empno = 1007
WHERE FactNo = 1