需要帮助格式化SQL Server XML兄弟查询的输出

时间:2016-01-17 23:16:06

标签: sql-server xml formatting

考虑以下SQL Server XML输出:

<CUSTOMER>
  <CUST_ID>TEST_CUSTOMER_01</CUST_ID>
  <ORG_CODE>MY_ORG</ORG_CODE>
  <CUSTOMER_TYPE CUST_TYPE="RETAIL" />
  <CUSTOMER_COUNTRY CTRY_CODE="US" />
</CUSTOMER>

它是由以下SQL语句生成的。

SELECT 
    CUSTOMER.CUST_ID, CUSTOMER.ORG_CODE,
    (SELECT CUSTOMER_TYPE.CUST_TYPE
     FROM CUSTOMER_TYPE
     WHERE CUSTOMER.CUST_ID = CUSTOMER_TYPE.CUSTOMER_ID
     FOR XML AUTO, TYPE),
   (SELECT CUSTOMER_COUNTRY.CTRY_CODE
    FROM CUSTOMER_COUNTRY
    WHERE CUSTOMER.CUST_ID = CUSTOMER_COUNTRY.CUSTOMER_ID
    FOR XML AUTO, TYPE)
FROM   
    CUSTOMER
WHERE 
    CUSTOMER.CUST_ID = 'TEST_CUSTOMER_01'
FOR XML AUTO, ELEMENTS
GO

要求输出看起来像下面的输出。将ELEMENTS替换为上述查询中的两个TYPE字词不会这样做。

我该怎么做?

<CUSTOMER>
   <CUST_ID>TEST_CUSTOMER_01</CUST_ID>
   <ORG_CODE>MY_ORG</ORG_CODE>
   <CUSTOMER_TYPE>
      <CUST_TYPE>SHIP_TO</CUST_TYPE>
   </CUSTOMER_TYPE>
   <CUSTOMER_COUNTRY>
     <CTRY_CODE>US</CTRY_CODE>
   </CUSTOMER_COUNTRY>
</CUSTOMER>

谢谢!

2 个答案:

答案 0 :(得分:1)

最佳(最佳使用效果!)为FOR XML PATH。只需命名它们,就可以非常直观,轻松地定义您想要的任何输出。

SELECT 
    'TEST_CUSTOMER_01' AS [CUST_ID]
    ,'MY_ORG' AS [ORG_CODE]
    ,'SHIP_TO' AS [CUSTOMER_TYPE/CUST_TYPE]
    ,'US' AS [CUSTOMER_COUNTRY/CTRY_CODE]
--FROM   
--    CUSTOMER
--WHERE 
--    CUSTOMER.CUST_ID = 'TEST_CUSTOMER_01'
FOR XML PATH('CUSTOMER')

答案 1 :(得分:0)

尝试此查询。

select CUST_ID,ORG_CODE,( SELECT CUSTOMER_TYPE.CUST_TYPE AS CUST_TYPE
  FROM   @customer_type CUSTOMER_TYPE
  WHERE  CUSTOMER.CUST_ID = CUSTOMER_TYPE.CUSTOMER_ID
  FOR XML  path (''),TYPE) AS 'CUSTOMER_TYPE' ,(
SELECT CUSTOMER_COUNTRY.CTRY_CODE as CTRY_CODE
  FROM   @customer_country CUSTOMER_COUNTRY
  WHERE  CUSTOMER.CUST_ID = CUSTOMER_COUNTRY.CUSTOMER_ID
 for xml path (''),TYPE
) AS 'CUSTOMER_COUNTRY'   from
@customer CUSTOMER
for xml auto, ELEMENTS

使用上述查询,您将得到

的结果
<CUSTOMER>
  <CUST_ID>TEST_CUSTOMER_01</CUST_ID>
  <ORG_CODE>MY_ORG</ORG_CODE>
  <CUSTOMER_TYPE>
    <CUST_TYPE>SHIP_TO</CUST_TYPE>
  </CUSTOMER_TYPE>
  <CUSTOMER_COUNTRY>
    <CTRY_CODE>US</CTRY_CODE>
  </CUSTOMER_COUNTRY>
</CUSTOMER>