如何在更新该行时将表中的特定行移动到另一个表

时间:2015-04-29 06:47:38

标签: sql-server

例如我有这两个表

Employee(FirstName, LastName, JoinDate, DesignationID,UpdateDate)
Employee_Designation_History(EmployeeID, DesignationID)

如果我更新员工表(更改DestinationID的{​​{1}}),我需要检索该员工的特定数据并保存到另一个表Employee中。

2 个答案:

答案 0 :(得分:1)

我猜你在第一张表中也有一个名为EmployeeId的列。 这可以通过trigger非常简单地完成:

CREATE TRIGGER Employee_Update ON Employee FOR UPDATE
AS
BEGIN
    IF UPDATE(DesignationID) -- only if the relevant column changed
    BEGIN
    INSERT INTO Employee_Designation_History (EmployeeID, DesignationID)
    SELECT d.EmployeeID, d.DesignationID
    FROM deleted d -- That's not a typo, deleted is the correct pseudo table
    LEFT JOIN Employee_Designation_History edh 
    ON(d.EmployeeID = edh.EmployeeID 
       AND d.DesignationID = edh.DesignationID)
    WHERE edh.EmployeeID IS NULL
    END
END

我选择deleted数据的原因是我猜你想在更改之前保留DesignationID的值。我已经在目标表上使用了LEFT JOIN,所以如果你已经有一个具有相同数据的记录,它将不会被触发器乘以。
我已使用UPDATE()函数确保相关列确实已更新。

答案 1 :(得分:0)

您需要的是Trigger,它识别该表上的更新语句并自动在另一个表中执行插入。

CREATE TRIGGER [update_history] ON Employee 
FOR UPDATE
AS
INSERT Employee_Designation_History (EmployeeID, DesignationID)
--Use the following insert to historicize the old (overwritten) data
SELECT ??, DesignationID,
FROM Employee 
    Join inserted
        On inserted.id = Employee.id
--Use the follong insert to historicize the new (updated) data
--INSERT Employee_Designation_History (EmployeeID, DesignationID)
--SELECT  ??, DesignationID
--FROM inserted

来源:Table history trigger in SQL Server?