如何在SQL Server中构建此XML?

时间:2018-04-20 19:40:58

标签: sql xml sql-server-2012 tags

我使用以下SQL创建一些临时表,然后使用那些我想生成XML的临时表。我能够生成一个XML,但我不能按照我想要的方式构建这个东西。

我想打开IndirectSalesMessage代码,然后打开Header代码,然后关闭<Header>代码,然后打开DIST代码,然后关闭{{最终关闭DIST标记之前的1}}标记。

以下是我现在在SQL中使用的代码及其功能。生成的XML位于&#34;我生成的&#34; XML下面。我实际想要生成的XML低于我想要生成的&#34; XML&#34;。

IndirectSalesMessage

当前生成的XML

-- Creation of #XML HEADER  
SELECT DISTINCT 
    [targetapplication], 
    [originatingapplication], 
    [interfacename], 
    '7320177' E1_num 
INTO
    #xml_header 
FROM   
    [CP].[dbo].[xmlforload] 

-- Creation of #DIST2 
SELECT 
    distributor_e1number, 
    debit_memo_number 
INTO
    #dist2 
FROM   
    #xml_dist 
WHERE  
    distributor_e1number = '7320177' 
    AND debit_memo_number = 'June20177320177' 

-- Creation of #XML
SELECT
    Header.[targetapplication], 
    Header.[interfacename], 
    Header.[originatingapplication], 
    DIST.distributor_e1number, 
    DIST.debit_memo_number 
FROM
    #xml_header Header 
INNER JOIN 
    #dist2 DIST ON header.e1_num = dist.distributor_e1number 
FOR XML PATH('Header'), ROOT('IndirectSalesMessage'), ELEMENTS

想要生成的XML

<IndirectSalesMessage>
   <Header>
      <TargetApplication>EnterpriseOne 9.1</TargetApplication>
      <InterfaceName>CA_Tracing</InterfaceName>
      <OriginatingApplication>Alliance-Model N</OriginatingApplication>
      <distributor_e1number>7320177</distributor_e1number>
      <debit_memo_number>June20177320177</debit_memo_number>
   </Header>
</IndirectSalesMessage>

1 个答案:

答案 0 :(得分:1)

创建XML

SELECT 
Header.targetapplicatioAS 'Header/Targetapplication', 
Header.interfacename AS 'Header/Interfacename', 
Header.originatingapplication AS 'Header/Originatingapplication',
DIST.distributor_e1number AS 'DIST/distributor_e1number',
DIST.debit_memo_number AS 'DIST/debit_memo_number'
FROM #xml_header Header 
INNER JOIN #dist2 DIST ON 
header.e1_num = dist.distributor_e1number 
FOR XML PATH('IndirectSalesMessage')