Control on XML elements nesting using FOR XML

倖福魔咒の 提交于 2019-12-02 08:08:40

Use @ in alias names to generate attributes in xml. Much simpler way to do this

SELECT NAME         AS [@Name],
       Surname      AS [@Surname],
       DateOfBirth  AS [@DateOfBirth],
       DepartmentID AS [department/@DepartmentID],
       AccessLevel  AS [department/security/@AccessLevel]
FROM   @Employees
FOR xml path('employee') 

Result:

<employee Name="John" Surname="Doe" DateOfBirth="1980-01-31">
  <department DepartmentID="100">
    <security AccessLevel="5" />
  </department>
</employee>
<employee Name="Mary" Surname="Rose" DateOfBirth="1971-02-27">
  <department DepartmentID="102">
    <security AccessLevel="3" />
  </department>
</employee>
<employee Name="Luke" Surname="Perry" DateOfBirth="1995-12-01">
  <department DepartmentID="104">
    <security AccessLevel="1" />
  </department>
</employee>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!