12

我的数据库中有许多表。这些表中的每一个都有一个触发器,该触发器在更新或删除时触发以记录对 AuditLog 表的更改。AuditLog 表包含以下内容:

Id (PK, int, not null) Action (nchar(1), not null) ActionDate (datetime, not null) ActionUser (nvarchar(100), not null) AuditData (XML(.), not null)

在我的触发器中,我正在执行以下操作:

DECLARE @auditBody XML
SET @auditBody = (select * from deleted as Root for xml auto, elements)
insert into dbo.AuditLog 
   (Action, ActionDate, ActionUser, AuditData)
   select Case
        When I.Id is not null then 'U'
        Else 'D'
       End as Action
     ,getdate() as ActionDate
     ,suser_name() as ActionUser
     ,@auditBody as AuditData
  From
    deleted D Left Join
    inserted I on D.Id = I.Id

这很好用,但是,我想做的是向 tablename 的 Root 元素添加一个属性,以便 AuditData xml 看起来像:

<Root tableName = "Person">
    <Id>132</Id>
    <FirstName>Ryan</FirstName>
    ...
</Root>

有什么方法可以通过 select from ... for xml 语句来实现这一点?

4

1 回答 1

23

在这个线程的帮助下,我能够想出这个并且它似乎有效:

select 'Person' as "@tableName",
 (select * from deleted for xml path('DataItem'), type)
 for xml path('Root')
于 2012-09-04T20:37:14.297 回答