SQL Server - 用于XML路径(嵌入元素)

时间:2016-06-10 09:24:33

标签: sql sql-server xml

INPUT:

SELECT EmpName AS [Name],
       EmpDOB       AS [Birthdate],
       EmpSalary        AS [WageAmount],
    Add1    AS [Address1],
    Add2    AS [Address2],
    Mobile  AS [Mobile]
FROM   Employee
FOR XML PATH

输出:(工作正常)

<Employee>
<Name>Conrad</Name>
<Birthdate>14-oct-76</BirthDate>
<WageAmount>10000</WageAmount>
<AdditionalInfo>
    <Address1>Washington DC</Address1>
    <Address2>DC</Address2>
    <Mobile>989898989</Mobile>
</AdditionalInfo>
</Employee>

我能够生成输出 - 但我希望将此元素添加到移动标记下方(CONTACT TYPE元素 - 我们如何添加它)

<Mobile>989898989</Mobile>
**<ContactType><mobilephone/></ContactType>**

1 个答案:

答案 0 :(得分:1)

;WITH Employee AS (
SELECT  'Conrad' as EmpName,
        '14-oct-76' as EmpDOB,
        10000 as EmpSalary,
        'Washington DC' as Add1,
        'DC' as Add2,
        989898989 as Mobile
)

SELECT EmpName AS [Name],
       EmpDOB       AS [Birthdate],
       EmpSalary        AS [WageAmount],
    Add1    AS [AdditionalInfo/Address1],
    Add2    AS [AdditionalInfo/Address2],
    Mobile  AS [AdditionalInfo/ContactType/Mobile]
FROM   Employee
FOR XML PATH ('Employee')

输出:

<Employee>
  <Name>Conrad</Name>
  <Birthdate>14-oct-76</Birthdate>
  <WageAmount>10000</WageAmount>
  <AdditionalInfo>
    <Address1>Washington DC</Address1>
    <Address2>DC</Address2>
    <ContactType>
      <Mobile>989898989</Mobile>
    </ContactType>
  </AdditionalInfo>
</Employee>