FOR XML SQL Query生成Record Header

时间:2016-10-18 19:34:24

标签: sql sql-server xml tsql subquery

我正在尝试使用FOR XML SQL Query生成XML。 XML的结构非常简单,除了需求要求额外的子元素,它必须在根元素和记录元素之间的文档顶部只出现一次。这是一个例子:

<Employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RecordHeader>
        <CreatedBy>My Organization</CreatedBy>
        <CreateDate>1900-01-01T01:01:01-06:00</CreateDate>
     </RecordHeader>
    <Employee>
        <EmployeeID>4</EmployeeID>
        <FirstName>Rob</FirstName>
        <LastName>Walters</LastName>
    </Employee>
    <Employee>
        <EmployeeID>168</EmployeeID>
        <FirstName>Rob</FirstName>
        <LastName>Caron</LastName>
     </Employee>
 </Employees>

我创建了一个FOR XML查询,但我似乎无法让它对RecordHeader正常工作。有什么建议?谢谢!

SELECT 
(SELECT 'My Organization' as [CreatedBy],
    CONVERT(VARCHAR(33), GetDate(), 126) as [CreateDate] FOR XML PATH('RecordHeader'), ELEMENTS),
EmployeeID, FirstName, LastName
FROM Employees
FOR XML PATH('Employee'), ROOT('Employees'), ELEMENTS

1 个答案:

答案 0 :(得分:4)

android:layout_marginBottom="15dp"

返回

Declare @Employee table (EmployeeID int,First_Name varchar(50),Last_Name varchar(50))
Insert into @Employee values
(1,'John','Smith'),
(2,'Jane','Doe'  )


Select (Select CreatedBy='My Organization',CreateDate=GetDate() For XML Path('RecordHeader'),Type ) 
      ,(Select * From @Employee For XML Path('Employee'),Type ) 
For XML Path ('Employees'),Type