我有 Employee 表。我想将该表的每一行转换为 XML
select d =
(select a.* for xml path('Root'), type, elements absent)
from MyEmployees a
以下是结果
第 1 行:
<Root>
<EmployeeID>1</EmployeeID>
<FirstName>Ken</FirstName>
<LastName>Sánchez</LastName>
<Title>Chief Executive Officer</Title>
<DeptID>16</DeptID>
</Root>
第 2 行:
<Root>
<EmployeeID>16</EmployeeID>
<FirstName>David</FirstName>
<LastName>Bradley</LastName>
<Title>Marketing Manager</Title>
<DeptID>4</DeptID>
<ManagerID>273</ManagerID>
</Root>
结果应类似于以下格式
<Root>
<Item Name="FirstName" type="String">Ken</Item>
<Item Name="LastName" type="String">Sánchez</Item>
</Root>
注意:DeptId 的类型应该是 Int。
我应该如何编写 SQL 查询?
我试过以下查询:
SELECT EmployeeID
,( SELECT firstname AS '@FirstName',lastname AS '@LastName' FROM MyEmployees AS b WHERE a.EmployeeID= b.EmployeeID FOR XML PATH('Employee') ) AS RowXML
FROM MyEmployees AS a
得到结果为:
1 <Employee FirstName="Ken" LastName="Sánchez"/>