SQL Server 2005 - TSQL For Xml query to get grouped departments and employees
-
29-10-2019 - |
Question
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
Company
andDepartment
are related throughFK
inDepartment
table that links toCompanyId
inCompany
table.Department
andEmployeeInDepartment
are related through 'FK' inEmployeeInDepartment
table that links toDepartmentId
inDepartment
table.
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')
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow