从审核中查找更改 table

Find changes from an audit table

我在审计中有数据 table,如下所示。 Fiddle 1, Fiddle 2

我需要从这个 table 中获取更新的列和数据详细信息。

预期结果是:

Employee Name : from Jone to Jhone

Employee Age : from 25 to 20

Employee Name : from Jhonny to Jone, Employee Age : from 18 to 25

我怎样才能做到这一点?

更新

更新记录时,我将插入两行以进行审核 table。第一条记录为 Old(auditDataState),更新前的数据,第二条记录为 New(auditDataState),更新后的数据。

所以每次更新在审计table中都有两条记录,分别是OldNew,其中包含旧值和新值。

我需要根据审计 table 中的 updateColumns 从审计 table 中获取更新的数据。(我将更新的列存储在 updateColumns 列中)。

我不需要第一行是 Employee Name : from Jone to Jhone。只需要确定更新的值。

这将提供您问题中指定的结果,尽管它远非明智或可扩展的解决方案。如果可能的话,我建议您完全重新审视您的变更审核:

declare @EmpAudit table (
      empID int
    , empName varchar(50)
    , empAge int
    , auditDataState varchar(50)
    , auditDMLAction varchar(50)
    , auditUser varchar(50)
    , auditDateTime datetime
    , updateColumns varchar(50)
);

insert into @EmpAudit values
      (1, 'Alex', 22, 'New', 'Insert','c@a.com',getdate(),''),
      (2, 'Jhonny', 18, 'New', 'Insert','c@a.com',getdate()-0.5,''),

      (2, 'Jhonny', 18, 'Old', 'Update','b@a.com',getdate()-1,'Employee Name, Employee Age'),
      (2, 'Jone', 25, 'New', 'Update','b@a.com',getdate()-1.5,'Employee Name, Employee Age'),

      (2, 'Jone', 25, 'Old', 'Update','a@a.com',getdate()-2,'Employee Age'),
      (2, 'Jone', 30, 'New', 'Update','a@a.com',getdate()-2.5,'Employee Age'),

      (2, 'Jone', 30, 'Old', 'Update','a@a.com',getdate()-3,'Employee Age'),
      (2, 'Jone', 20, 'New', 'Update','a@a.com',getdate()-3.5,'Employee Age'),

      (2, 'Jone', 20, 'Old', 'Update','a@a.com',getdate()-4,'Employee Name'),
      (2, 'Jhone', 20, 'New', 'Update','a@a.com',getdate()-4.5,'Employee Name');

with d as
(
    select empID
            ,empName
            ,empAge
            ,auditDataState
            ,auditDMLAction
            ,auditUser
            ,auditDateTime
            ,updateColumns
            ,row_number() over (partition by empID order by auditDateTime) as rn
    from @EmpAudit
)
select case when o.empName <> n.empName then 'Employee Name : from ' + o.empName + ' to ' + n.empName else '' end
      +case when charindex(',',o.UpdateColumns) > 0 then ', ' else '' end
      +case when o.empAge <> n.empAge then 'Employee Age : from ' + cast(o.empAge as varchar(3)) + ' to ' + cast(n.empAge as varchar(3)) else '' end as Change
from d as o
    join d as n
        on o.empID = n.empID
            and o.updateColumns = n.updateColumns
            and o.rn = n.rn+1
            and n.auditDataState = 'New'
where o.auditDataState = 'Old';

输出:

Change
-----------------------------------------------------------------
Employee Name : from Jone to Jhone
Employee Age : from 30 to 20
Employee Age : from 25 to 30
Employee Name : from Jhonny to Jone, Employee Age : from 18 to 25