gpt4 book ai didi

SQL 服务器 : Nesting Elements with FOR XML PATH

转载 作者:行者123 更新时间:2023-12-02 17:27:09 25 4
gpt4 key购买 nike

努力编写可以在 XML 中生成嵌套元素的查询。谁能帮忙

输入:

SELECT EmpName AS [Name],
EmpDOB AS [Birthdate],
EmpSalary AS [WageAmount],
Add1 AS [Address1],
Add2 AS [Address2],
Mobile AS [Mobile]
FROM Employee
FOR XML PATH

输出:(这有附加信息作为嵌套元素)

<Employee>
<Name>Conrad</Name>
<Birthdate>14-oct-76</BirthDate>
<WageAmount>10000</WageAmount>
<AdditionalInfo>
<Address1>Washington DC</Address1>
<Address2>DC</Address2>
<Mobile>989898989</Mobile>
</AdditionalInfo>
</Employee>

最佳答案

在这种情况下,最简单的方法是使用正斜杠分隔符在列别名中指定路径:

SELECT EmpName AS [Name],
EmpDOB AS [Birthdate],
EmpSalary AS [WageAmount],
Add1 AS [AdditionalInfo/Address1],
Add2 AS [AdditionalInfo/Address2],
Mobile AS [AdditionalInfo/Mobile]
FROM Employee
FOR XML PATH ('Employee')

您还可以使用在选择列中返回 XML 的子查询来实现。像这样:

SELECT EmpName AS [Name],
EmpDOB AS [Birthdate],
EmpSalary AS [WageAmount],
(select
Add1 AS [AdditionalInfo/Address1],
Add2 AS [AdditionalInfo/Address2],
Mobile AS [AdditionalInfo/Mobile]
from Employee EmpAddInfo
where EmpAddInfo.EmployeeID=Employee.EmployeeID
FOR XML PATH('AdditionalInfo'), TYPE
)
FROM Employee
FOR XML PATH ('Employee')

在你的情况下这样做很愚蠢,因为字段都在同一个表中,但如果你有一个要加入的详细表,你会这样做。

关于SQL 服务器 : Nesting Elements with FOR XML PATH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37734539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com