努力编写可以在XML中生成嵌套元素的查询。任何人都可以帮忙
INPUT:
SELECT EmpName AS [Name],
EmpSalary AS [WageAmount],
Add1 AS [Address1],
Add2 AS [Address2],
Mobile AS [Mobile]
FROM Employee
FOR XML PATH
TABLE DATA(对于具有不同地址的emoployee,存在2条记录)
Conrad Jagger 12345 London UK 9191919191
Conrad Jagger 12345 Coventry UK 9191919191
预期的输出:(这有附加信息作为嵌套元素)
<Employee>
<Name>Conrad</Name>
<WageAmount>10000</WageAmount>
<AdditionalInfo>
<PersonAddress>
<Address1>London</Address1>
<Address2>UK</Address2>
<Mobile>919191919191</Mobile>
</PersonAddress>
<PersonAddress>
<Address1>Coventry</Address1> --->Second address
<Address2>UK</Address2>
<Mobile>919191919191</Mobile>
</PersonAddress>
</AdditionalInfo>
</Employee>
如果您有单个记录,此查询有效,我不知道如何使这个工作为多个记录,我得到
SELECT EmpName AS [Name],
EmpSalary AS [WageAmount],
Add1 AS [AdditionalInfo/Address1],
Add2 AS [AdditionalInfo/Address2],
Mobile AS [AdditionalInfo/Mobile]
FROM Employee
FOR XML PATH ('Employee')
答案 0 :(得分:1)
我希望表格中有一个uniqe id列。由于您还没有提供该列,我正在加入EmpName列。
试试这个
SELECT EmpName AS [Name],
EmpSalary AS [WageAmount],
(SELECT
Add1 AS [PersonAddress/Address1],
Add2 AS [PersonAddress/Address2],
Mobile AS [PersonAddress/Mobile] FROM Employee B WHERE EmpName = A.EmpName
FOR XML PATH('AdditionalInfo'),type)
FROM Employee A
GROUP BY EmpName,EmpSalary
FOR XML PATH ('Employee')