This may sound stupid (newer to SQL Server), but I am looking for help directing me on how to write a FOR XML query in SQL Serverto export a table to a very specific nested format. The program that I am importing the information into needs it this way or it will not work properly.
This is a sample of the table I am using.
Below is the output that I am looking for. I am able to generate the single row one with this query, but I am looking to nest it and make it look like the example below. I am not sure how to get the XML wrapper to be the value from the field. The end software that will be using this can only use ids that have numbers so that is why I have to format it the way that I am. Hoping someone can provide guidance and direction with this.
SELECT *
FROM Tbl_Store
FOR XML Path('Store')
<STORE>
<box1>
<item1>
<size>10</size>
<weight>15</weight>
</item1>
<item2>
<size>20</size>
<weight>25</weight>
</item2>
<item3>
<size>30</size>
<weight>35</weight>
</item3>
<item4>
<size>40</size>
<weight>45</weight>
</item4>
<item5>
<size>50</size>
<weight>55</weight>
</item5>
</box1>
<box2>
<item1>
<size>10</size>
<weight>15</weight>
</item1>
<item2>
<size>20</size>
<weight>25</weight>
</item2>
<item3>
<size>30</size>
<weight>35</weight>
</item3>
<item4>
<size>40</size>
<weight>45</weight>
</item4>
<item5>
<size>50</size>
<weight>55</weight>
</item5>
</box2>
</Store>
Edit Finally version. Thanks to Shnugo
`SELECT ROW_NUMBER() OVER(ORDER BY Box) AS [@ID]
,M.Box as [BoxName]
,(
SELECT m2.Item AS [@ID]
,m2.Size AS [size]
,m2.[Weight] AS [weight]
FROM @mockup m2
WHERE m2.Box = m.Box
ORDER BY m2.Item
FOR XML PATH('item'),TYPE
)
FROM @mockup m
GROUP BY m.Box
FOR XML PATH('box'),ROOT('Store')`
