Can anyone spot the problem with my trigger?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • daveperry
    New Member
    • Jan 2008
    • 1

    Can anyone spot the problem with my trigger?

    In SQL Server 2005, I have an update trigger on a table. The purpose of this trigger is to set or clear a DeactivatedDate field whenever the IsActive field is changed. Also to write an audit record keeping a record of the change. Here is an excerpt from the trigger:

    Code:
    DECLARE @prevIsActive BIT		
    DECLARE @newIsActive BIT
    DECLARE @id BIGINT
    
    SELECT @newIsActive = IsActive, @id = RecordId
    FROM inserted
    
    IF UPDATE(IsActive)	
    BEGIN	
    	SELECT @prevIsActive = IsActive FROM deleted
    	IF @newIsActive < @prevIsActive
    	BEGIN	--deactivated
    		UPDATE Customers 
    		SET DeactivatedDate = GETDATE() 
    		WHERE CustomerId=@id 
    	END
    	ELSE
    	BEGIN	--activated
    		UPDATE Customers 
    		SET DeactivatedDate = NULL 
    		WHERE CustomerId=@id 
    	END
    
    	--Add an entry to the audit table with OpType 6 indicating deactivated and OpType 7 indicating activated.
    	INSERT INTO AuditCustomers (CustomerId, OpType, UserId)
    	SELECT i.CustomerId, CASE i.IsActive WHEN 1 THEN 7 ELSE 6 END, i.UserId
    	FROM Inserted AS i
    	INNER JOIN Deleted AS d ON i.CustomerId = d.CustomerId
    	WHERE i.IsActive <> d.IsActive
    END
    This trigger is working in 99% of cases. However, in the other 1% of cases, when a customer is deactivated, the audit record is created correctly with OpType=6, proving that the trigger must have fired, but the DeactivatedDate remains null. How is this possible, can anybody tell me?
Working...