Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Based on Recep's answer (see comments) I created the following solution for this problem:</p> <p><strong>1. Create a recursive function</strong></p> <pre><code>CREATE function SelectChild(@key as int) returns xml begin return ( select IdIndustry as "@key", ParentId as "@parentkey", IndustryCode as "@Code", IndustryName as "@Name", dbo.SelectChild(IdIndustry) from tblIndustryCodes where ParentId = @key for xml path('record'), type ) end </code></pre> <p><strong>2. Build a SELECT statement, that calls the function</strong></p> <pre><code>SELECT IdIndustry AS "@key", '' AS "@parentkey", IndustryCode as "@Code", IndustryName as "@Name", dbo.SelectChild(IdIndustry) FROM dbo.tblIndustryCodes WHERE ParentId is null FOR XML PATH ('record') </code></pre> <p>This creates a hierarchical XML, no matter how deep the tree actually is:</p> <pre><code>&lt;record key="1" parentkey="" Code="IND" Name="Industry"&gt; &lt;record key="2" parentkey="1" Code="AUTO" Name="Automotive" /&gt; &lt;record key="3" parentkey="1" Code="PHARM" Name="Pharmaceuticals" /&gt; &lt;/record&gt; &lt;record key="4" parentkey="" Code="FIN" Name="Finance"&gt; &lt;record key="5" parentkey="4" Code="CFIN" Name="Corporate Finance"&gt; &lt;record key="6" parentkey="5" Code="CMRKT" Name="Capital Markets" /&gt; &lt;/record&gt; &lt;/record&gt; &lt;record key="7" parentkey="" Code="CON" Name="Cosulting"&gt; &lt;record key="8" parentkey="7" Code="IMPL" Name="Implementation" /&gt; &lt;record key="9" parentkey="7" Code="STRAT" Name="Strategy" /&gt; &lt;/record&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload