3

I have a table structure like below :

SELECT  
    [EmpID], [EmpName],
    [DeptName],
    [BirthDate] 
FROM
    [dbo].[Employees]

I want to convert this table data into XML and the final output will be like below:

<Employees>
    <Department DeptName="ABC"> 
        <Employee EmpID="1">
            <EmpName>Davolio</EmpName>
            <BirthDate>10/12/1989</BirthDate>
        </Employee>
        <Employee EmpID="2">
            <EmpName>Andrew</EmpName>    
            <BirthDate>05/02/1985</BirthDate>
        </Employee>
    </Department>
    <Department DeptName="DEF"> 
        <Employee EmpID="3">
            <EmpName>David</EmpName>
            <BirthDate>11/09/1982</BirthDate>
        </Employee> 
    </Department>`enter code here
</Employees>

1 Answer 1

3

Try this

SELECT  [DeptName] 
        ,(  SELECT  [EmpID],
                    [EmpName],
                    [BirthDate] 
            FROM @table E
            WHERE   E.DeptName = D.DeptName
            FOR XML PATH ('Employee'),TYPE
        )
FROM    @table D
GROUP BY [DEPTNAME]
FOR XML PATH ('Department'),type,ROOT('Employees')
Sign up to request clarification or add additional context in comments.

1 Comment

@saiv One tiny hint: If you want to have the DeptName and the EmpID as attributes (like in the given example), you must add an Alias AS [@DeptName] resp. AS [@EmpID]. And be aware, that XML will use the ISO8601 and therefore the date will look like 1982-09-11T00:00:00

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.