Converting rows to XML format in SQL Server

Viewed 5952

I have requirement like below.

enter image description here

And ddl and dml script for above image is

CREATE TABLE #example
    ([CCP_DETAILS_SID] int, [ACCOUNT_GROWTH] int, [PRODUCT_GROWTH] int, [PROJECTION_SALES] numeric(22,6), [PROJECTION_UNITS] numeric(22,6), [PERIOD_SID] int)
;

INSERT INTO #example
    ([CCP_DETAILS_SID], [ACCOUNT_GROWTH], [PRODUCT_GROWTH], [PROJECTION_SALES], [PROJECTION_UNITS], [PERIOD_SID])
VALUES
    (30001, 0, 0, 1505384.695, 18487.25251, 1801),
    (30001, 0, 0, 1552809.983, 18695.75536, 1802),
    (30001, 0, 0, 1595642.121, 18834.75725, 1803),
    (30002, 0, 0, 10000.32, 18834.75725, 1801),
    (30002, 0, 0, 1659124.98, 18834.75725, 1802),
    (30002, 0, 0, 465859546.6, 18834.75725, 1803)
;

And i have to convert above results to xml format like below (Output).

ccp_details_sid           xml_format_string

30001                      <period>  
                           <period_sid period_sid=1801>
                           <PROJECTION_SALES>1505384.695</PROJECTION_SALES>
                           <PROJECTION_UNITS>18487.25251<PROJECTION_UNITS>
                           <ACCOUNT_GROWTH>0</ACCOUNT_GROWTH>
                           <PRODUCT_GROWTH>0</PRODUCT_GROWTH>
                           </period_sid>
                            <period_sid period_sid=1802>
                           <PROJECTION_SALES>1552809.983</PROJECTION_SALES>
                           <PROJECTION_UNITS>18695.75536<PROJECTION_UNITS>
                           <ACCOUNT_GROWTH>0</ACCOUNT_GROWTH>
                           <PRODUCT_GROWTH>0</PRODUCT_GROWTH>
                           </period_sid>
                           <period_sid period_sid=1802>
                           <PROJECTION_SALES>1595642.121</PROJECTION_SALES>
                           <PROJECTION_UNITS>18834.75725<PROJECTION_UNITS>
                           <ACCOUNT_GROWTH>0</ACCOUNT_GROWTH>
                           <PRODUCT_GROWTH>0</PRODUCT_GROWTH>
                           </period_sid>
                           </period>

30002                      Same like above      

I am new to XML so couldn't able to do it quickly. I have used Marc_s solution with cross apply but can't able to achieve it.

Note: my major goal is, in above image if we see there are three records for single ccp_details_sid so I want to convert it as one row by using XML (mentioned above).

1 Answers
Related