0

我的应用程序上有两个表(我正在尝试创建一个错误跟踪器)。一个我可以添加记录/问题,一个是问题的历史。

因此,第二个 (Bugs_Shadow) 表将与第一个 (Bugs) 表一起创建新记录,然后,当有人尝试修复时,我可以更新表 1 上的问题。单击更新时,我希望它将更新行作为一个整体添加到第二个表中,但也保留原始记录。因此,无论何时进行更改,都会在 Bugs_Shadow 表中创建一条新记录。我希望这是有道理的?

我创建了这个触发器:

CREATE TRIGGER [tr_Bugs_Insert]
    ON [dbo].[Bugs]
    AFTER UPDATE, INSERT
    AS
    BEGIN
        INSERT INTO Bugs_Shadow (BugID, [User], Date, Subject, Description, [Source Code], [Current State])
        SELECT BugID, [User], Date, Subject, Description, [Source Code], [Current State]
        FROM Bugs

    END
    GO

它可以在第二个表中创建相同的条目,但是当我更新第一个表中的条目时,它在第二个表中执行相同的操作,而我希望它创建一个除了更改之外相同的新记录由用户制作。

希望那里有一些帮助。这是我第一次尝试触发器,我花了一段时间才达到这个阶段。

谢谢

4

1 回答 1

0

You need to triggers here:

  • One after the insert in one table to insert it into the other
  • One before update in one table to insert it into the other

CREATE TRIGGER [tr_Bugs_Insert] 
    ON [dbo].[Bugs]
    AFTER INSERT
    AS
    BEGIN
        INSERT INTO Bugs_Shadow (BugID, [User], Date, Subject, Description, [Source Code], [Current State])
        SELECT BugID, [User], Date, Subject, Description, [Source Code], [Current State]
        FROM Bugs
END
GO

CREATE TRIGGER [tr_Bugs_Update]
    ON [dbo].[Bugs]
    BEFORE UPDATE
    AS
    BEGIN
        INSERT INTO Bugs_Shadow (BugID, [User], Date, Subject, Description, [Source Code], [Current State])
        SELECT BugID, [User], Date, Subject, Description, [Source Code], [Current State]
        FROM Bugs
END

EDIT

MS SQL doesn't support before triggers, so the above is not valid. You could use an INSTEAD trigger. With an INSTEAD trigger, only the trigger gets executed and not the original statement. So what you should do in that trigger is insert the old value in one table and update the other table.

For more info, see this question: How can I do a BEFORE UPDATED trigger with sql server?

There are also some answers in there specifying alternative solutions.

于 2017-01-08T23:10:10.950 回答