I have a flattened table that contains columns that represent groups that need to be displayed in XML. Example data:
Market, Label, Style, Type
XXX, YYY, JJJ, 111
XXX, YYY, JJJ, 222
XXX, YYY, JJJ, 333
XXX, YYY, JJJ, 444
XXX, YYY, LLL, 111
XXX, YYY, LLL, 222
XXX, YYY, LLL, 333
XXX, YYY, LLL, 444
Using T-SQL what would be the best way to output the following:
<Market value=XXX>
<label value=YYY>
<Style value=JJJ>
<Type value=111>
</Type>
...
</Style>
<Style value=LLL>
...
</Style>
</label>
</Market>
Can I do this by using the XML Explicit clause in SQL Server?
Formatting complex XML documents in T-SQL is a fool’s errand. It can be done – maybe – but then you come back to it a month later and what you’ve got is incomprehensible.
It’s much, much easier to either write a method in C# or whatever that processes a
DataReaderto produce the XML, or write an XSLT transform that converts the XML emitted from the query into whatever specialized format you’re trying to create.