更新的T-SQL触发器审核

时间:2017-05-10 01:07:41

标签: sql-server tsql triggers

我需要做一个"触发更新"用于将表位置的更改插入审计表。

我知道如何访问新旧值的插入/删除但我似乎无法找到我需要做的事情来获取已更新的不同列。(我知道光标使用等)。

这是我现在获得的代码(法语中的sry)

ALTER TRIGGER T_U_Locations ON Locations
FOR UPDATE 
AS
BEGIN

--Definition des valeurs
DECLARE @tempDuChangement VARCHAR(30);
DECLARE @nomDuChampChange VARCHAR(64);
DECLARE @idLocation INT;
DECLARE @ancienneV VARCHAR(50);
DECLARE @nouvelleV VARCHAR(50);
DECLARE @raison VARCHAR(50);


--Aquisition des valeurs sur les changement apportés
SET @tempDuChangement = CONVERT( VARCHAR(30) , CURRENT_TIMESTAMP );

SET @nomDuChampChange = --HERE GOES THE CURRENT UPDATED COLUMN
SET @idLocation = (SELECT inserted.id FROM inserted);

SET @ancienneV = (SELECT /*HERE GOES THE CURRENT UPDATED COLUMN*/ FROM deleted);
SET @nouvelleV = (SELECT /*HERE GOES THE CURRENT UPDATED COLUMN*/ FROM inserted);

-- Crée une nouvelle entré dans la table Audits avec les information relative
INSERT INTO Audits
VALUES
(
    @tempDuChangement,
    @nomDuChampChange,
    @ancienneV,
    @nouvelleV,
    @idLocation,
    'raison test'
)
END

1 个答案:

答案 0 :(得分:0)

假设id是唯一的(并且在更新中没有更改),我想你想要:

insert into Audits (time, columnName, oldValue, newValue . . . )  -- always include the column list
    select Current_Timestamp, v.colname, v.oldValue, v.newValue, . . .
    from inserted i join
         deleted d
         on i.id = d.id outer apply
         (values ('col1', d.col1, o.col1),
                 ('col2', d.col2, o.col2),
                 ('col3', d.col3, o.col3),
                 . . .
         ) v(colname, oldValue, newValue)
     where v.oldValue <> v.newValue or
           v.oldValue is null and v.newValue is not null or
           v.oldValue is not null and v.newValue is null;

基本上,您使用outer apply按列拆分数据,因此您需要包含所有列。然后where子句获取已修改的子句。

相关问题