0

我知道如何进行联合并从不同的表中吐出一个 XML 文件,但是,我需要创建一个临时表来容纳我需要成为 XML 文件一部分的 3 条记录。结构与其他表完全相同。

我该怎么做呢?

select * from
(
  select ID_Number as [ID], CLAST as [name/last], CFIRST as [name/first], '' as extension]
  from dbo.users as a 
  union all
  select PID as [ID], NID as [name/last], NAME as [name/first],  PREF_TITLE as [extension] 
  from dbo.Person
) as a
FOR XML PATH('employee'), ROOT('employees')

所以我需要 3 行数据,它们将填写 ID、姓名/姓氏、姓名/名字和扩展名。

最好的建议是什么?

4

1 回答 1

0

创建临时表,填充它并将其作为另一个添加到查询中UNION ALL。有不同类型的临时表,这里有一些使用表变量的代码,最简单的类型...

DECLARE @tempTable TABLE
(
  ID int,
  Surname varchar(30),
  FirstName varchar(30),
  Title varchar(30)
)

INSERT @tempTable VALUES (7, 'Siobhan', 'Green', 'Ms')
INSERT @tempTable VALUES (8, 'Paul', 'Jones', 'Mr')
INSERT @tempTable VALUES (9, 'Sam', 'Morrison', 'Mrs')

SELECT * FROM
(
  SELECT ID_Number as [ID], CLAST as [name/last], CFIRST as [name/first], '' as [extension]
  FROM users as a 
  UNION ALL
  SELECT PID, NID, NAME, PREF_TITLE 
  FROM Person
  UNION ALL
  SELECT ID, Surname, FirstName, Title
  FROM @tempTable
) as a
FOR XML PATH('employee'), ROOT('employees')

Click here to see it in action at SQL Fiddle

于 2013-05-24T19:47:38.377 回答