Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何向SQL的Select for xml生成的xml的根元素添加属性_Sql Server - Fatal编程技术网

Sql server 如何向SQL的Select for xml生成的xml的根元素添加属性

Sql server 如何向SQL的Select for xml生成的xml的根元素添加属性,sql-server,Sql Server,我的数据库中有很多表。每个表都有一个触发器,在更新或删除时触发,以记录对AuditLog表的更改。AuditLog表包含以下内容: DECLARE @auditBody XML SET @auditBody = (select * from deleted as Root for xml auto, elements) insert into dbo.AuditLog (Action, ActionDate, ActionUser, AuditData) select Case

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

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
Id PK,int,不为空 操作nchar1,不为空 ActionDate日期时间,不为空 ActionUser nvarchar100,不为空 AuditData XML.,不为空

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

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的根元素添加一个属性,这样AuditData xml看起来像:

<Root tableName = "Person">
    <Id>132</Id>
    <FirstName>Ryan</FirstName>
    ...
</Root>
有什么方法可以通过从…中选择来实现这一点吗。。。对于xml语句?

在thread的帮助下,我想出了这个方法,它似乎很有效:

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