For a database holding 3 tables:
- Company
- Department
- EmployeeInDepartment
I would like to a xml like below:
<Companies>
<Company>
<CompanyName></CompanyName>
<CompanyId></CompanyId>
<..></..>
<Departments>
<Name></Name>
<..></..>
<Employees>
<Employee>
<FirstName></FirstName>
<LastName></LastName>
.. .. ..
</Employee>
.. .. ..
</Employees>
</Departments>
.. .. ..
</Company>
.. .. ..
</Companies>
Where the company is repeating (tags), departments inside company are repeating (tags) and Employee inside departments are repeating (tags) by repeating I mean there are more than one number of these element & not the data.
Relations
CompanyandDepartmentare related throughFKinDepartmenttable that links toCompanyIdinCompanytable.DepartmentandEmployeeInDepartmentare related through 'FK' inEmployeeInDepartmenttable that links toDepartmentIdinDepartmenttable.
Query:
execute the below on PUBS database and check the xml, it will have more than one Jobs with id 10
select jobs.job_id 'JobId',
job_desc 'Desc',
(
select emp_id 'EmployeeId',fname 'FirstName',lname 'LastName' from employee where job_id = jobs.job_id for xml path('Emploees'),type
)
from jobs
inner join
employee on jobs.job_id = employee.job_id
for xml path('employees')
You need to do "nested"
FOR XMLstatements - that should give you what you're looking for.See e.g. Richard Dingwall's Nested FOR XML results with SQL Server that shows how to do this. Of course, you can easily nest more than two levels...