创建一个触发器来计算一段数据被更改的次数SQL

时间:2017-03-23 20:28:32

标签: sql sql-server sql-server-2008

我目前正在编写一个SQL触发器,用于记录一段数据的更改次数。它会将其写入专栏' PrevAddrNum'在tblCustomer中,触发器执行正常但在测试时我得到错误消息说"事务在触发器中结束批处理已经中止"。这是我的下面的代码,任何帮助将不胜感激!

CREATE TRIGGER PrevAddr ON tblCustomer
AFTER UPDATE
AS
IF UPDATE(CustomerAddress)
BEGIN
  UPDATE tblCustomer
  SET PrevAddrNum = PrevAddrNum + 1
END

1 个答案:

答案 0 :(得分:3)

假设您的表具有CustomerID或类似字段,则应仅更新受影响的记录。

CREATE TRIGGER PrevAddr ON tblCustomer
AFTER UPDATE
AS
BEGIN TRY
  UPDATE     tblCustomer
  SET        PrevAddrNum = PrevAddrNum + 1
  FROM       tblCustomer tc
  INNER JOIN deleted 
  ON         tc.CustomerID = deleted.CustomerID
  INNER JOIN inserted 
  ON         tc.CustomerID = inserted.CustomerID
  WHERE      deleted.CustomerAddress <> inserted.CustomerAddress
END TRY
BEGIN CATCH
    -- just to get the error 
    -- create a new table ErrorLog and save the errors there
    DECLARE @ErrorMsg VARCHAR(MAX), @ErrorNumber INT, @ErrorProc sysname, ErrorLine INT 

    SELECT @ErrorMsg = ERROR_MESSAGE(), @ErrorNumber = ERROR_NUMBER(), 
           @ErrorProc = ERROR_PROCEDURE(), @ErrorLine = ERROR_LINE();

    INSERT INTO ErrorLog (ErrorMsg,  ErrorNumber,  ErrorProc,  ErrorLine)
    VALUES               (@ErrorMsg, @ErrorNumber, @ErrorProc, @ErrorLine)
END CATH