简体   繁体   English

对于带有临时表的XML Union

[英]For XML Union with a temp table

I know how to do union's and spit out an XML file from different tables, however, I need to create a temp table that will house 3 records that I need to be a part of the XML File. 我知道如何进行合并并从不同的表中吐出XML文件,但是,我需要创建一个临时表来容纳3条记录,这些记录需要成为XML文件的一部分。 The structure is exactly the same as the other tables. 结构与其他表完全相同。

How would I go about doing this? 我将如何去做呢?

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')

So I would need 3 lines of data, which will fill ID, name/last, name/first and extension. 因此,我需要3行数据,这些数据将填充ID,名称/姓氏,名称/名字和扩展名。

What would be the best recommendation? 最好的建议是什么?

Create the temp table, fill it and add it into the query as another UNION ALL . 创建临时表,填充它,并将其作为另一个UNION ALL添加到查询中。 There are different types of temporary table , here's some code that uses a table variable, the most simple type... 临时表不同类型 ,这是一些使用表变量的代码,这是最简单的类型...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM