使用SQL FOR XML语句生成XML注释

时间:2009-07-20 15:39:34

标签: sql-server xml

背景:我正在使用SQL FOR XML查询生成更大的XML文档(HL7 CDA文档)。遵循约定,我们需要在此XML节点之前包含节注释,以便在将节点重新组合到更大的文档中时,它们更易于阅读。

以下是预期输出的示例:

<!-- 
********************************************************
  Past Medical History section
********************************************************
-->

<component>
    <section>
        <code code="10153-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>
        <title>Past Medical History</title>
        <text>
            <list>
                <item>COPD - 1998</item>
                <item>Dehydration - 2001</item>
                <item>Myocardial infarction - 2003</item>
            </list>
        </text>
    </section>
</component>

以下是我为呈现上述XML而构建的SQL FOR XML语句:

SELECT     '10153-2' AS [section/code/@code], '2.16.840.1.113883.6.1' AS [section/code/@codeSystem], 'LOINC' AS [section/code/@codeSystemName], 
                      'Past Medical History' AS [section/title],
            (SELECT     [Incident] + ' - ' + [IncidentYear] as "item"
             FROM       [tblSummaryPastMedicalHistory] AS PMH
             WHERE      ([PMH].[Incident] IS NOT NULL) AND ([PMH].[PatientUnitNumber] = [PatientEncounter].[PatientUnitNumber])
             FOR XML PATH('list'), TYPE
            ) as "section/text"
FROM         tblPatientEncounter AS PatientEncounter
WHERE     (PatientEncounterNumber = 6)
FOR XML PATH('component'), TYPE

虽然我可以从控制函数中插入重新组合这些XML片段的注释到主文档中,但我们的目标是使用输出生成注释以避免文档构造错误。

我尝试过一些东西,但是在使用SELECT语句生成注释时遇到了麻烦。我尝试过一个简单的字符串,但无法获得换行符的语法。有什么建议吗?

1 个答案:

答案 0 :(得分:11)

示例:

SELECT [EmployeeKey]
      ,[ParentEmployeeKey]
      ,[FirstName]
      ,[LastName]
      ,[MiddleName]
      ,[DepartmentName] AS "comment()"
  FROM [AdventureWorksDW2008].[dbo].[DimEmployee]
  FOR XML PATH('Employee'),ROOT('Employees')

产生

<Employees>
  <Employee>
    <EmployeeKey>1</EmployeeKey>
    <ParentEmployeeKey>18</ParentEmployeeKey>
    <FirstName>Guy</FirstName>
    <LastName>Gilbert</LastName>
    <MiddleName>R</MiddleName>
    <!--Production-->
  </Employee>
  <Employee>
    <EmployeeKey>2</EmployeeKey>
    <ParentEmployeeKey>7</ParentEmployeeKey>
    <FirstName>Kevin</FirstName>
    <LastName>Brown</LastName>
    <MiddleName>F</MiddleName>
    <!--Marketing-->
  </Employee>
</Employees>