简体   繁体   中英

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. 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.

What would be the best recommendation?

Create the temp table, fill it and add it into the query as another 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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