views:

29

answers:

1

Hi All,

I am planning on using a recursive table in my data model so that I can support an undetermined number of children that can live under a parent. My example is a Table of Contents where I don't know how deep my subsections will be under a chapter.

The issue I am stumbling over is what techniques do folks use to populate there DB once they have defined a recursive table? By that I mean if I have a list of items that refer to a chapter -> Section -> Subsection...when I load the Chapter, Section, and Subsection into the model I need to identity the lowest level of the hierarchy and assign that value to the Item I am loading (Foreign Key - I would assume) so that I can always get all of the info about that item.

So for example:

Item: 2A-GHI: Chapter: 2 Section: A SubSection: GHI

If I have my data loaded like

ID|TOCID|TOC_VALUE|PARENT_ID  
1|Chapter|2|-1  
2|Section|A|1  
3|SubSection|GHI|2    

How do i tie the item to GHI so that I can set the FK to the Recursive Table for that Item? Do you use all three values as a Key and set that as another column in the table so that on load you can identity the lowest level?

Like So:

ID|TOCID|TOC_VALUE|PARENT_ID|Key  
1|Chapter|2|-1|2  
2|Section|A|1|2_A  
3|SubSection|GHI|2|2_A_GHI

I can load the recursive table and I am using a CTE to recurse the data, but I am not sure what the best method is to load the recursive data and tie that data into the model so that my item has a FK to the Table of Contents data.

A: 

You need a column for the row's parent ID.

ID|TOCID|TOC_VALUE|parent 
1|Chapter|2|0
2|Section|A|1 
3|SubSection|GHI|2

a parentID of 0 or null means it's a root (chapter) node

Beth
thanks beth I had accidentally left that piece out....just really stuck on tieing the item to the lowest level and using that Table Of Contents value as my FK in my items table.
scarpacci
I think you're going to need to load all the nodes before creating your TOC. If you pass through all the rows once, you can build it without additional references.
Beth
What I have done so far is build "Keys" for the Table Of contents values that I can align with my items so that when I load my Items I can see what the lowest level is in the TOC data that they align with so I can get the ID from the TOC table and use that as my FK in my line Item data. Not sure how else to do it.
scarpacci
That should work. You can always improve it later if you come up with/find a better idea.
Beth