2

Consider the following SQL Server XML output:

<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>

It was generated by the following SQL statement.

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

It's required that the output look like the output below. Substituting ELEMENTS for the two TYPE words in the query above doesn't do it.

How then do I do it?

<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>

Thanks!

2 Answers 2

1

The best (best in usage and performance!) is FOR XML PATH. It is very intuitive and easy to define any output you want simply by naming them.

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Wow.. a much better answer than my answer.:)
Thanks for a great answer!
0

Try this query.

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

Using the above query you will get the result as

<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.