0

我有 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"/>

4

1 回答 1

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

SQL小提琴

于 2013-09-25T06:50:31.733 回答