1

我有以下脚本可以为一个表生成 XML。我需要稍微修改一下,以便它在一个 XML 查询中从 3 个不同的表中提取它。我不确定如何修改它,以便它在 1 个查询中完成。我应该只创建一个存储过程吗?:

SELECT 
CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
LastName AS [name/last], 
FirstName AS [name/first], 
'Employee' AS [persontype], 
email AS email
FROM dbo.Employees AS sd
WHERE (IsActive = 'Y') FOR XML PATH('employees')      

另一张表是:

dbo.承包商

对此的查询略有不同:

SELECT 
CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
LastName AS [name/last], 
FirstName AS [name/first], 
'Contractor' AS [persontype], 
email AS email
FROM dbo.Employees AS sd
WHERE (IsActive = 'Y') FOR XML PATH('employees')     

最后一个是:

dbo.实习生

SELECT 
CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
LastName AS [name/last], 
FirstName AS [name/first], 
'Intern' AS [persontype], 
email AS email
FROM dbo.Employees AS sd
WHERE (IsActive = 'Y') FOR XML PATH('employees')     

唯一更改的字段是此处的第 5 行

4

2 回答 2

1

希望这会有所帮助:

select * from (
 SELECT 
 CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
 LastName AS [name/last], 
 FirstName AS [name/first], 
 'Employee' AS [persontype], 
 email AS email
 FROM dbo.Employees AS sd
 WHERE (IsActive = 'Y') 
 union
 SELECT 
 CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
 LastName AS [name/last], 
 FirstName AS [name/first], 
 'Contractor' AS [persontype], 
 email AS email
 FROM dbo.Employees AS sd
 WHERE (IsActive = 'Y'
 union
 SELECT 
 CAST(EmployeeNumber AS varchar(9)) AS [employee/id], 
 LastName AS [name/last], 
 FirstName AS [name/first], 
 'Intern' AS [persontype], 
 email AS email
 FROM dbo.Employees AS sd
 WHERE (IsActive = 'Y')) employees
 FOR XML PATH('employees')  
于 2013-05-06T14:52:16.513 回答
0

为什么你不能UNION这三个查询?这会将 3 个单独的查询视为单个数据集。

于 2013-05-06T14:45:42.280 回答