更新触发器之后将旧记录插入另一个表

时间:2018-09-27 12:46:05

标签: sql-server tsql triggers

我有MedicalAllowance表,我希望从该表中获取历史记录表“ MedicalAllowanceHistory”,我想创建触发器以在更新后执行此操作 MedicalAllowance表将数据复制到“ MedicalAllowanceHistory”表。哪种方法更好。

医疗津贴表

ID | Employee_ID | Limit | Used | Balance

MedicalAllowanceHistory表

ID | Employee_ID | Limit | Used | Balance

3 个答案:

答案 0 :(得分:2)

您可以为此使用触发器
但是我还要存储事件的日期和事件的类型(插入,更新或删除)
这是一个让您入门的示例

CREATE trigger tr_UID_MedicalAllowance on dbo.MedicalAllowance
after update, insert, delete
as
begin
    set nocount on

    declare @Insert bit = 0
    declare @Update bit = 0
    declare @Delete bit = 0

    --find out why we where triggered
    if (exists(select 1 from inserted)) and (exists(select 1 from deleted))
        set @Update = 1
    else if (exists(select 1 from inserted))
        set @Insert = 1
    else if (exists (select 1 from deleted))
        set @Delete = 1

    if @Update = 1
    begin
         insert into MedicalAllowanceHistory (
                     MedicalAllowanceID, 
                     HistoryDate, 
                     HistoryEvent, 
                     other columns...)
         select i.MedicalAllowanceID,
                getdate(),
                'UPDATED',
                i.other columns...
         from   inserted i
    end

    if @Insert = 1
    begin
         insert into MedicalAllowanceHistory (
                     MedicalAllowanceID, 
                     HistoryDate, 
                     HistoryEvent, 
                     other columns...)
         select i.MedicalAllowanceID,
                getdate(),
                'INSERTED',
                i.other columns...
         from   inserted i
    end

    if @Delete = 1
    begin
         insert into MedicalAllowanceHistory (
                     MedicalAllowanceID, 
                     HistoryDate, 
                     HistoryEvent, 
                     other columns...)
         select d.MedicalAllowanceID,
                getdate(),
                'DELETED',
                d.other columns...
         from   deleted d
    end
end

在更新的情况下,也可以存储新旧值,新值在inserted表中,而旧值在deleted表中。
在这种情况下,update部分可能看起来像这样

if @Update = 1
begin
     insert into MedicalAllowanceHistory (
                 MedicalAllowanceID, 
                 HistoryDate, 
                 HistoryEvent, 

                 NewLimit,
                 OldLimit,

                 other columns...)
     select i.MedicalAllowanceID,
            getdate(),
            'UPDATED',

            i.Limit,
            d.Limit,

            other columns...
     from   inserted i
       inner join deleted d on i.MedicalAllowanceID = d.MedicalAllowanceID
end

答案 1 :(得分:0)

您可以使用以下示例解决问题:

CREATE TRIGGER tg_MedicalAllowance ON MedicalAllowance
AFTER UPDATE, INSERT, DELETE
AS
BEGIN
  INSERT MedicalAllowanceHistory
  SELECT ID,Employee_ID,Limit,Used,balance
  FROM deleted
END

答案 2 :(得分:0)

我建议您使用“更改数据捕获”而不是“触发器”。在此解决方案中,SQL会跟踪所有更改。如果您需要了解更多信息,请单击here