我发现无法将属性添加到查询中的现有节点。您当然可以从您的表中创建一个临时表并修改临时表中的 XML,一次添加一个属性。
另一种选择是接受这很难的事实,并决定要构建一个包含所有数据但不是以您想要的确切方式的 XML。例如这个查询。
select *
from YourTable
for xml raw
会给你这样的XML。
<row EntryID="1" TableName="Manufacturers" AuditDate="2013-01-30T15:48:24.690" ChangeType="U">
<AuditValue>
<row ManufacturerID="6" ManufacturerName="AMES999" IsDeleted="0" Concurrency="AAAAAAABTAk=" />
</AuditValue>
</row>
或者你可以使用这个
select EntryID as '@EntryID',
TableName as '@TableName',
AuditDate as '@AuditDate',
ChangeType as '@ChangeType',
AuditValue as '*'
from YourTable
for xml path('row')
获取 XML
<row EntryID="1" TableName="Manufacturers" AuditDate="2013-01-30T15:48:24.690" ChangeType="U">
<row ManufacturerID="6" ManufacturerName="AMES999" IsDeleted="0" Concurrency="AAAAAAABTAk=" />
</row>
如果您准备好让这个变得非常丑陋,您可以尝试结合使用 XML 和字符串操作。
select cast(replace(cast(AuditValue as nvarchar(max)), '/>', '') +
stuff(cast((
select EntryID, TableName, AuditDate, ChangeType
for xml raw, type
) as nvarchar(max)) ,1 , 4, '') as xml) as AuditValue
from YourTable
结果:
<row ManufacturerID="6"
ManufacturerName="AMES999"
IsDeleted="0"
Concurrency="AAAAAAABTAk="
EntryID="1"
TableName="Manufacturers"
AuditDate="2013-01-30T15:48:24.690"
ChangeType="U" />
SQL小提琴