2015-06-19 77 views
3

我有兩個表測試和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'建議立即進行刪除插入

+1

'從INSERTED I'選擇@ID = I.ID當插入/ udate/delete sql影響多行時,這不起作用。 – ughai

回答

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