2012-05-05 57 views
3

我在xml輸出中遇到了一個小問題。帶有動態SQL的SQL Server XML輸出

I need to get xml structure like this:

,這裏是我的程序,它會列出所有的員工和一些基於輸入自己的個人信息 的。

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 

我得到的是here 但我仍然無法弄清楚如何添加DPR節點。

謝謝

回答

3

您需要使用SQL Server 2005中的FOR XML PATH功能,以及相關子查詢 - 沿此線的東西:

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'別名使用這個作爲一個相關子查詢然後包裹升員工對於一個給定的部門IST成<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> 

你那麼這個XML片段添加到最外部SELECT它創建<department>節點,你應該得到所需的輸出。

欲瞭解更多信息有關FOR XML PATH看到:

+1

謝謝你,它完美的作品!現在事情更容易理解。 – justartem

+0

@Caerus:是的,對於SQL Server的XML支持,「FOR XML PATH」模式是一個非常有用的補充! –