3

我面临一个关于 xml 输出的小问题。

我需要得到这样的xml结构:

这是我的程序,它将根据输入列出所有员工及其一些个人信息。

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

我得到的是这里, 但我仍然不知道如何添加 DPR 节点。

谢谢

4

1 回答 1

2

您需要使用FOR XML PATHSQL Server 2005 中的功能和相关子查询 - 类似于以下内容:

SELECT 
    d.Department_ID AS '@f_Department_ID',
    d.Department_Name AS '@f_Department_name',
    (SELECT 
        e.BusinessEntityID AS '@f_Employee_ID',
        e.FirstName AS '@f_First_Name',
        e.LastName AS '@f_Last_name',
            e.Email AS '@f_email',
        e.Salary AS '@f_salary'
     FROM
        dbo.Employee e
     WHERE
        e.Department_ID = d.Department_ID
     FOR XML PATH('dp'), TYPE
    ) AS 'dpr' 
FROM 
    dbo.Department d 
WHERE 
    d.DepartmentID IN (.......) 
ORDER BY 
    d.DepartmentID
FOR XML PATH('department'), ROOT('table')

基本上,最里面的查询为单个员工创建 XML 元素

<dp f_Employee_ID="6" f_First_Name="Jossef" f_Last_name="Goldberg" f_salary="998320692" />

将其用作具有别名的相关子查询AS 'dpr'then 将给定部门的员工列表包装到<dpr>标签中:

<dpr>
  <dp f_Employee_ID="4" f_First_Name="Rob" f_Last_name="Walters" f_salary="112457891" />
  <dp f_Employee_ID="11" f_First_Name="Ovidiu" f_Last_name="Cracium" f_salary="974026903" />
  <dp f_Employee_ID="12" f_First_Name="Thierry" f_Last_name="D'Hers" f_salary="480168528" />
  <dp f_Employee_ID="13" f_First_Name="Janice" f_Last_name="Galvin" f_salary="486228782" />
</dpr>

SELECT然后将此 XML 片段添加到创建节点的最外层<department>,您应该会获得所需的输出。

有关更多信息,FOR XML PATH请参阅:

于 2012-05-05T20:36:15.400 回答