I’m faced with a little question on xml output.
I need to get xml structure like this:
and here is my procedure, it’ll list all the employees and some of their personal info
based on input.
CREATE PROC getDeptEmployees(@deptList varchar(500))
AS
BEGIN
SET NOCOUNT ON
DECLARE @Query varchar(600)
SET @Query = '
SELECT department.DEPARTMENT_ID [f_Department_ID], department.DEPARTMENT_NAME [f_Department_name],
dp.Employee_id [f_Employee_ID], dp.First_name [f_First_Name],
dp.Last_Name [f_Last_name], dp.Email [f_email], dp.Salary [f_salary]
FROM dbo.Employees dp
JOIN DEPARTMENTS department
ON dp.DEPARTMENT_ID = department.DEPARTMENT_ID
WHERE dp.Department_id IN (' + @deptList + ')
for XML AUTO, ROOT(''table'')'
EXEC(@Query)
END
GO
What I get is here
but I still can’t figure out how to add the DPR node.
Thank you
You need to use the
FOR XML PATHfunctionality in SQL Server 2005, and a correlated subquery – something along the lines of this:Basically, the innermost query creates the XML element for a single employee
Using this as a correlated subquery with an alias of
AS 'dpr'then wraps the list of employees for a given department into a<dpr>tag:You then add this XML fragment to the outer most
SELECTwhich creates the<department>node, and you should get the desired output.For more info on
FOR XML PATHsee: