更新IM_ServiceRequest表后,应将相同的更改插入到IM_ServiceRequest _Hx表中

时间:2014-03-18 13:20:42

标签: sql-server

CREATE TRIGGER [dbo].[INSERT_IM_ServiceRequest_Hx] 
ON [dbo].[IM_ServiceRequest] AFTER INSERT
AS 
BEGIN
    INSERT INTO  IM_ServiceRequest_Hx
      SELECT * 
      FROM IM_ServiceRequest

    PRINT 'AFTER INSERT Trigger fired.'
END

1 个答案:

答案 0 :(得分:2)

您的当前触发器会将所有行插入第二个表 - 每次INSERT发生时。通过查看触发器中的Inserted伪表来更改此信息:

CREATE TRIGGER [dbo].[INSERT_IM_ServiceRequest_Hx] 
ON [dbo].[IM_ServiceRequest] AFTER INSERT
AS 
BEGIN
    INSERT INTO IM_ServiceRequest_Hx(col1, col2, ...., colN)
      SELECT col1, col2, ..., colN 
      FROM Inserted

    PRINT 'AFTER INSERT trigger fired.'
END

<强>更新

同样基本上也适用于AFTER UPDATE个触发器,因为在这种情况下,修改行的 new 值也存储在Inserted中:

CREATE TRIGGER [dbo].[UPDATE_IM_ServiceRequest_Hx] 
ON [dbo].[IM_ServiceRequest] AFTER UPDATE
AS 
BEGIN
    INSERT INTO IM_ServiceRequest_Hx(col1, col2, ...., colN)
      SELECT col1, col2, ..., colN 
      FROM Inserted

    PRINT 'AFTER UPDATE trigger fired.'
END

我还建议始终明确定义您要在INSERT INTO ....语句中使用的列,并在选择时使用相同的列列表而不是SELECT * Inserted伪表