T-SQL查询FOR XML输出,如何正确地将XML查询格式化为规范

时间:2015-11-28 21:33:39

标签: sql sql-server xml formatting

嗨,谢谢您的提前时间。我很擅长从SQL查询格式化XML输出,所以在这里它:)我需要格式化我的FOR XML SQL查询(在SSMS 2012中)以匹配这种格式:

<HR_Data>
    <ClientInfo>
      <OrganizationOID>XXXX</OrganizationOID>
      <ClientId>XXXX</ClientId>
    </ClientInfo>
    <EmployeeHRData>
      <Employee_ID>XXXX</Employee_ID>
      <SocialSecurityNumber>XXXX</SocialSecurityNumber>
      ....
    </EmployeeHRData>
    <EmployeeHRData>
      <Employee_ID>XXXX</Employee_ID>
      <SocialSecurityNumber>XXXX</SocialSecurityNumber>
      ....
    </EmployeeHRData>
</HRData>

所以用文字来说,ClientInfo标题包含公司特有的信息,然后是为每个员工重复的EmployeeHRData部分,所有这些部分都包含在HRData标记中。

到目前为止,我有以下输出(客户信息重复,而不是只出现一次,并且有一个不属于的FinalOutputTable标记):

<HR_Data>
  <FinalOutputTable>
    <ClientInfo>
      <OrganizationOID>XXXX</OrganizationOID>
      <ClientId>XXXX</ClientId>
    </ClientInfo>
    <EmployeeHRData>
      <Employee_ID>XXXX</Employee_ID>
      <SocialSecurityNumber>XXXX</SocialSecurityNumber>
      ....
    </EmployeeHRData>
  </FinalOutputTable>
  <FinalOutputTable>
    <ClientInfo>
      <OrganizationOID>XXXX</OrganizationOID>
      <ClientId>XXXX</ClientId>
    </ClientInfo>
    <EmployeeHRData>
      <OrganizationOID>XXXX</OrganizationOID>
      <ClientId>XXXX</ClientId>
      ....
    </EmployeeHRData>
  </FinalOutputTable>
</HRData>

由以下内容生成:

SELECT (SELECT 'XXXX' AS 'OrganizationOID', 'XXXX' AS 'ClientId'
        FOR XML PATH (''), TYPE) ClientInfo

        ,(SELECT [AOID] AS AssociateOID
                ,ISNULL([Employee Identifier], '') AS Employee_ID
                ,ISNULL(SSN, '') AS SocialSecurityNumber
                ,.........

        FOR XML PATH (''), TYPE) EmployeeHRData            


INTO #FinalOutputTable
FROM XXXX
WHERE XXXX
ORDER BY XXXX

SELECT * FROM #FinalOutputTable AS FinalOutputTable
FOR XML AUTO, ROOT('HR_Data'), ELEMENTS

1 个答案:

答案 0 :(得分:1)

要在ClientInfo元素中使用嵌套的ClientId元素,请使用

Select 11 as "ClientInfo/ClientId"

因此,您可以使用正斜杠来定义xml结果中值的位置。

编辑:如果要为一个客户返回文档,可以使用下面的代码。

Declare @HR_Data xml
Set @HR_Data=
(Select HR_Data.ClientInfo
 from
(
Select  (
     SELECT 'XXXX' AS 'OrganizationOID', 'XXXX' AS 'ClientId'
     FOR XML PATH (''), TYPE
    ) ClientInfo
) HR_Data 
FOR XML PATH(''), ROOT('HR_Data'))


Declare @EmployeeHRData xml
Set @EmployeeHRData=
(SELECT   
      [AOID] AS AssociateOID
      ,ISNULL([Employee Identifier], '') AS Employee_ID
      ,ISNULL(SSN, '') AS SocialSecurityNumber
       ,.........
       from table_name
   FOR XML PATH('EmployeeHRData'), TYPE
   )


SET @HR_Data.modify(
    'insert sql:variable("@EmployeeHRData")
    as last into (/HR_Data[1])')
Select @HR_Data