对于具有两个父节点和多个子节点的XML结构?

时间:2016-01-22 03:38:28

标签: sql-server xml

我需要将XML结构如下:

function test() {
       if (document.getElementById('div1').style.display == 'block') {
            document.getElementById('div1').style.display = 'none';
        }
        else{
            document.getElementById('div1').style.display = 'block';
        }
    }

我有一个FOR XML查询,其结构如下:

   <Loans>
    <Loan>
       <GUID></GUID>
       <LoanFolder></LoanFolder>
       <LastModified></LastModified>
       <TotalMonthlyPayment></TotalMonthlyPayment>
       <AgentCompanyName></AgentCompanyName>
    <LoanSecondaryStatusDates>
       <LoanSecondaryStatus>
          <StatusName>Name</StatusName>
          <StatusDate>Date</StatusDate>
        </LoanSecondaryStatus>
       <LoanSecondaryStatus>
        <StatusName>Name</StatusName>
        <StatusDate>Date</StatusDate>
       </LoanSecondaryStatus>
    </LoanSecondaryStatusDates>
 </Loan>
</Loans>

这让我很接近,但却错过了顶级&#34; LoanSecondaryStatusDates&#34;根节点。如何添加此根节点? http://sqlfiddle.com/#!6/d672a/2/0

注意:我能够使用此XSL添加节点:

    SELECT 
  [GUID] 
  ,[LOANFOLDER]
  ,[LASTMODIFIED]
  ,[LASTIMPORTED]
  ,[TotalMonthlyPayment]
  ,[AgentCompanyName],
   (
   SELECT 
    'Borrower Docs Sent/Req' as 'StatusName',
    CASE WHEN t.BorrowerDocsSent IS NOT NULL THEN t.BorrowerDocsSent ELSE '' END as 'StatusDate'

FROM Encompass_loanData as t
WHERE t.[GUID] = E.[GUID]
FOR XML PATH('LoanSecondaryStatus'), TYPE
  ),
  (
   SELECT 
    t.BorrowerCity as 'StatusName',
    t.[GUID] as 'StatusDate'

FROM Encompass_loanData as t
WHERE t.[GUID] = E.[GUID]
FOR XML PATH('LoanSecondaryStatus'), TYPE
  )

From Encompass_loanData E
WHERE [LASTMODIFIED] >= '20160121'
FOR XML PATH ('Loan'), type, root('Loans')

1 个答案:

答案 0 :(得分:1)

这是一个可能的SQL查询,根据您的SQL Fiddle表结构构建,它将生成所需的XML格式:

SELECT 
       [GUID] 
      ,[LOANFOLDER]
      ,[LASTMODIFIED]
      ,[LASTIMPORTED]
      ,[TotalMonthlyPayment]
      ,[AgentCompanyName]
      ,(
        SELECT * FROM
        (
            SELECT 
                CONVERT(VARCHAR(100), t.TotalMonthlyPayment) as 'StatusName',
                t.[GUID] as 'StatusDate'

            FROM [Sample] as t
            WHERE t.[GUID] = E.[GUID]
            UNION
            SELECT 
                'Borrower Docs Sent/Req' as 'StatusName',
                CASE WHEN t.LastModified IS NOT NULL THEN CONVERT(VARCHAR(25), t.LastModified, 126) ELSE '' END as 'StatusDate'

            FROM [Sample] as t
            WHERE t.[GUID] = E.[GUID]
        ) AS s
        FOR XML PATH('LoanSecondaryStatus'), TYPE, root('LoanSecondaryStatusDates')
       )

From [Sample] E
FOR XML PATH ('Loan'), type, root('Loans')

<强> sqlfiddle demo

基本上,内部FOR XML PATH将返回包含在一个LoanSecondaryStatus父级中的LoanSecondaryStatusDates个元素,以及一个用于生成UNION数据的LoanSecondaryStatus子句。除此之外,上述查询中看到的所有转换都需要使UNION的两边都返回兼容的数据类型,否则查询将以转换错误终止。