更新记录插入历史表而不是旧记录

时间:2015-06-19 13:08:49

标签: sql sql-server tsql

我有两个表Test和TestHistory

CREATE TABLE [dbo].[TEST](
    [ID] [int] NULL,
    [Name] [varchar](10) NULL,
    [Status] [char](1) NULL,
    [CreatedDate] [datetime] NULL
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[Test_History](
    [ID] [int] NULL,
    [Name] [varchar](10) NULL,
    [Status] [char](1) NULL,
    [CreatedDate] [datetime] NULL
) ON [PRIMARY]

GO

INSERT INTO TEST ([ID],[Name],[Status],[CreatedDate])values (1,'Mohan','A',GETDATE())

创建触发器:

ALTER TRIGGER [dbo].[trg_Test] 
     ON [dbo].[TEST]
     FOR UPDATE 
     AS

     Declare @ID INT;
     Declare @Name varchar(10);
     Declare @Status CHAR(2);
     Declare @CreatedDate DATETIME;


     Select @ID = I.ID from INSERTED I
     Select @Name = I.Name from INSERTED I
     Select @Status = I.Status from INSERTED I
     Select @CreatedDate = I.CreatedDate from INSERTED I


     INSERT INTO [dbo].[Test_history]
           ([ID]
           ,[Name]
           ,[Status]
           ,[CreatedDate]
           )

          SELECT @ID,
                 @Name,
                 @Status,
                 GETDATE()

                    FROM INSERTED I

           WHERE @ID = [ID] 

当我更新记录时

Update [TEST] SET Status = 'I'然后应该插入带有Status = 'A'的旧记录,但是我更新它的内容已插入Testhistory表而不是旧记录  我在哪里做错了以及如何插入旧值

就像我更新Status = 'I'并在历史表Status = 'A'中插入

2 个答案:

答案 0 :(得分:6)

您需要INSERT DELETED而不是INSERTED

请参阅此处的示例Understanding SQL Server inserted and deleted tables for DML triggers

答案 1 :(得分:2)

与Karl提到的一样,您需要将已删除的表引用为旧的更新行信息。除此之外,当您更新多行时,现有代码不起作用。你需要的是这样的东西。

ALTER TRIGGER [dbo].[trg_Test] 
     ON [dbo].[TEST]
     FOR UPDATE 
     AS
       INSERT INTO [dbo].[Test_history]
       (
       [ID],
       [Name],
       [Status],
       [CreatedDate]
       )
      SELECT ID,
             Name,
             Status,
             GETDATE()
      FROM deleted d