0

Struggling to write query which can generate nested elements in XML. Can anyone help

INPUT:

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

TABLE DATA (2 records exist for emoployee with different addresses)

Conrad Jagger   12345    London   UK    9191919191
Conrad Jagger   12345    Coventry UK    9191919191

Expected OUTPUT: (this has additional info as a nested element)

    <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>

This query works if you have single record coming, i don't know how to make this work for multiple records which im getting

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 Answer 1

1

I hope there is an uniqe id column in the table. As you haven't provided that column, i am joining on EmpName column for instance.

Try this

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') 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.