Question

I have a table which contains two column.

 Agency Code   MCI Numb
----------------------------
      a            1234 
      a            12345
      b            11

I need to write a query in SQl so that it will give data in following format.

< AgencyCode>
    <ID>a</ID>
    <MCI_NUMB>1234</MCI_NUMB>
    <MCI_NUMB>12345</MCI_NUMB>
</AgencyCode>
< AgencyCode>
    <ID>b</ID>
    <MCI_NUMB>11</MCI_NUMB>
</AgencyCode>
Was it helpful?

Solution

You would need to use FOR XML / XPATH queries.

Try something like this:

SELECT ID
     , CAST(MCI_Numb AS xml).query('/') AS MCI_Numbs
  FROM(SELECT DISTINCT ID
                     , (SELECT MCI_Numb
                          FROM myTable
                          WHERE ID = T.ID
                          FOR XML PATH(''))AS MCI_Numb
         FROM myTable AS T)AS T2
  FOR XML PATH ('AgencyCode');

Take a look at this link: It explains in detail how to manipulate the sql server into xml and vice versa.

OTHER TIPS

You probably need to take a look at :

FOR XML: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx

and

PIVOT: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx

The first will allow you to return xml, the second will allow you to pivot your data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top