I have a data set that looks something like this:
Gender | Age | Name
Male | 30 | Bill
Female | 27 | Jenny
Female | 27 | Debby
Male | 44 | Frank
And I’m trying to display this as specially formatted HTML code:
<ul>
<li>Male
<ul>
<li>30
<ul>
<li>Bill</li>
</ul>
</li>
<li>44
<ul>
<li>Frank</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li>Female
<ul>
<li>27
<ul>
<li>Jenny</li>
<li>Debby</li>
</ul>
</li>
</ul>
</li>
</ul>
I tried using FOR XML but that didn’t give the results I was looking for. It didn’t remove the multiple Gender and Age fields returned. As you can see in this HTML it is compounding it all and only giving duplicates at the end node.
How would something like this be achieved in SQL Server?
Here is a really ugly way formulating the HTML manually. There is a good reason this doesn’t belong in SQL Server. I’m sure some XML guru will come along and embarrass me with a much more straightforward method (I played with Simon Sabin’s solution but couldn’t translate it to your requirement), but for now:
Result – not exactly what you asked for in terms of white space, but identical HTML rendering:
EDIT For a much cleaner solution, as well as a lot of drama and a good demonstration of why @ZeeTee is the most annoying user on StackOverflow, see Mikael’s solution to the follow-up question:
Return Select Statement as formatted HTML (SQL 2005)