我和我一起有员工表。 我想将该表的每一行转换为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>
注意:类型应为Int for DeptId。
我应该如何编写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"/>
答案 0 :(得分:0)
select (
select T.Name as [@Name],
T.Type as [@type],
T.Value as [*]
from (values
('EmployeeID', 'Int', cast(E.EmployeeID as varchar(10))),
('FirstName', 'String', E.FirstName),
('LastName', 'String', E.LastName),
('Title', 'String', E.Title),
('DeptID', 'Int', cast(E.DeptID as varchar(10)))
) as T(Name, Type, Value)
for xml path('Item'), root('Root'), type
)
from MyEmployees as E