我有以下脚本可以为一个表生成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.Contractors
对此的查询略有不同:
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.Interns
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行
答案 0 :(得分: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')
答案 1 :(得分:0)
为什么你不能UNION
这三个查询?这会将3个单独的查询视为单个数据集。