【问题标题】:T-SQL Trigger audit for update更新的 T-SQL 触发器审计
【发布时间】:2017-10-08 11:41:23
【问题描述】:

我需要执行“更新触发器”以将表位置的更改插入到审计表中。

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

这里是我目前得到的代码(抱歉是法语)

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

【问题讨论】:

  • inserteddeleted 是表,因此它们可以表示集合操作的结果。假设触发器总是只处理一行,而设计触发器通常是一个糟糕的计划。如果您绝对确定不会超过一排,那么添加对行数的检查,并使用RaIsErrorThrow 明确告知稍后来的人他们有试图执行不可接受的语句。 (if ( select Count(*) from inserted ) > 1 RaIsError( 'FooTable_Insert: No more than one row may be processed.', 25, 42 ) with log)

标签: sql-server tsql triggers


【解决方案1】:

假设 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 子句然后获取已修改的子句。

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2013-06-20
    • 2021-05-20
    相关资源
    最近更新 更多