2012-09-04 12 views
11

我在我的數據庫中有很多表。這些表中的每個表都有一個觸發器,用於更新或刪除以將更改記錄到AuditLog表中。審計日誌表包含以下:如何添加一個屬性到由SQL的Select for xml生成的xml的根元素

ID(PK,INT,不爲空) 動作(NCHAR(1),不爲空) ActionDate(日期時間,不爲空) ActionUser(nvarchar的(100),不爲空) 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 

這個偉大的工程,但是,我希望做的就是添加了什麼一個屬性給表名的Root元素,以便AuditData xml看起來像這樣:

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

是否有任何方法來完成這與選擇從... for xml語句?

回答

18

this線程以幫助,我能想出這個和它似乎工作:

select 'Person' as "@tableName", 
(select * from deleted for xml path('DataItem'), type) 
for xml path('Root') 
相關問題