插入历史表后,我需要再次更新

时间:2015-06-10 11:12:04

标签: sql sql-server

我有Transaction表和Transaction History表。我写了更新触发器它将在历史表中维护更新的记录,它不允许复制,但是如果更新状态为Y或N,如何更新ISActive列.Record正在维护但是如何更新对同一记录所做的更改重复

ALTER TRIGGER [dbo].[trg_Transaction] 
     ON [dbo].[Transaction_Details]
     FOR UPDATE 
     AS

     Declare @ApplicationNo varchar(20);
     Declare @PaymentID varchar(20);
      Declare @CreatedBy varchar(20)
     DECLARE @CreatedDate DATETIME ;
     DECLARE @UpdatedDate DATETIME ;
     DECLARE @UpdatedBy VARCHAR(20) ;
     DECLARE @IsActive CHAR(2)

     Select @ApplicationNo = I.ApplicationNo from INSERTED I
     Select @PaymentID = I.PaymentID from INSERTED I
     Select @CreatedDate = CAST(I.CreatedDate AS DATETIME) from INSERTED I
     Select @UpdatedDate = CAST(I.UpdatedDate  AS DATETIME)from INSERTED I
     Select @UpdatedBy = I.UpdatedBy from INSERTED I
     Select @IsActive = I.IsActive from INSERTED I

     INSERT INTO [BPS].[dbo].[Transaction_Details_History]
           ([ApplicationNo]
           ,[PaymentID]
           ,[CreatedBy]
           ,[UpdatedDate]
           ,[UpdatedBy]
           ,[IsActive])

          SELECT @ApplicationNo,
                 @PaymentID, 
                 @CreatedBy,
                 @UpdatedDate,
                 @UpdatedBy,
                 @IsActive
                    FROM INSERTED I
           WHERE NOT EXISTS 
           (SELECT 
                [ApplicationNo]
           ,[PaymentID]
           ,[CreatedBy]
           ,[UpdatedDate]
           ,[UpdatedBy]
           ,[IsActive] 

                     FROM [Transaction_Details_History]
           WHERE @ApplicationNo = [ApplicationNo] 
)
GO

1 个答案:

答案 0 :(得分:1)

您可以使用MERGE来实现此目的,您只需检查是否存在记录,是否更新记录,如果没有,则

ALTER TRIGGER [dbo].[trg_Transaction] 
ON [dbo].[Transaction_Details]
FOR UPDATE 
AS
BEGIN

MERGE dbo.Transaction_Details_History AS h
USING inserted AS i
    ON i.ApplicationNo = h.ApplicationNo
WHEN MATCHED THEN UPDATE
    SET PaymentID = i.PaymentID,
        CreatedBy = i.CreatedBy,
        UpdatedDate = i.UpdatedDate,
        UpdatedBy = i.UpdatedDate,
        IsActive = i.IsActive
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (ApplicationNo, PaymentID, CreatedBy, UpdatedDate, UpdatedBy, IsActive)
    VALUES (i.ApplicationNo, i.PaymentID, i.CreatedBy, i.UpdatedDate, i.UpdatedBy, i.IsActive)

END
GO

如果您只想在IsActive更改时更新历史记录,则可以向MATCHED子句添加条件:

MERGE dbo.Transaction_Details_History AS h
USING inserted AS i
    ON i.ApplicationNo = h.ApplicationNo
WHEN MATCHED AND i.IsActive <> h.IsActive THEN UPDATE
    SET PaymentID = i.PaymentID,
        CreatedBy = i.CreatedBy,
        UpdatedDate = i.UpdatedDate,
        UpdatedBy = i.UpdatedDate,
        IsActive = i.IsActive
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (ApplicationNo, PaymentID, CreatedBy, UpdatedDate, UpdatedBy, IsActive)
    VALUES (i.ApplicationNo, i.PaymentID, i.CreatedBy, i.UpdatedDate, i.UpdatedBy, i.IsActive)