Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

[4633] Tree structures in ASP.NET and SQL Server

Last post 03-11-2007 2:56 PM by toranaga. 25 replies.
Page 2 of 2 (26 items) < Previous 1 2
Sort Posts: Previous Next
  • 04-29-2005 9:54 AM In reply to

    Optimized way of doing this?

    good article but wanted to know which of the two ways are more optimized
    using xml or the example you have given
    • Post Points: 0
  • Advertisement

    • Red Gate Software

    Advertisement

    Want to boost your .NET application performance?

    Some developers always seem to write efficient and lightening-fast code. What is their secret? It’s ANTS Profiler. “We improved the performance of the application up to 10 times” Dan Ports, Intrigma.

    Try it for yourself now.

  • 09-19-2005 4:50 PM In reply to

    • webandit
    • Not Ranked
    • Joined on 01-04-2005
    • New Member
    • Points 20

    Where did my post go

    Why was my post about making the database and code more efficient removed?
    • Post Points: 0
  • 09-22-2005 7:20 PM In reply to

    • jcelko
    • Not Ranked
    • Joined on 09-22-2005
    • New Member
    • Points 20

    trees & hierarchies in SQL

    Hasn't anyone read a copy of TREES & HIERARCHIES IN SQL?  There are sooo many better ways of doing this without any proprietary code.

    • Post Points: 0
  • 11-03-2005 3:11 PM In reply to

    • James Crowley
    • Top 10 Contributor
    • Joined on 12-07-2000
    • United Kingdom
    • Guru
    • Points 15,030
    • SystemAdministrator
    Hi Joe - thanks for posting! What do you mean by "proprietary" code exactly? I know this isn't the same method that you recommend (which I actually didn't come across until after I wrote this article)... but it's all still just SQL stuff....
    • Post Points: 0
  • 11-03-2005 3:12 PM In reply to

    • James Crowley
    • Top 10 Contributor
    • Joined on 12-07-2000
    • United Kingdom
    • Guru
    • Points 15,030
    • SystemAdministrator
    It's still there - you just need to change the drop down on the right hand side to extend the range of old posts that are displayed.
    • Post Points: 0
  • 11-03-2005 3:14 PM In reply to

    • James Crowley
    • Top 10 Contributor
    • Joined on 12-07-2000
    • United Kingdom
    • Guru
    • Points 15,030
    • SystemAdministrator
    Unless I've misunderstood you... the point of the lineage field was not to soley indicate its parent, but the entire path up the tree, so we could easily perform queries against this... i'm not sure how easy the same queries would be to perform using the method you describe?
    • Post Points: 0
  • 11-03-2005 8:06 PM In reply to

    • jcelko
    • Not Ranked
    • Joined on 09-22-2005
    • New Member
    • Points 20
    Yoiu can do your heirarchies & trees in pure declarative SQL without using any proprieary 4GL like PL/SQL,  T-SQL, etc.
    • Post Points: 0
  • 11-03-2005 11:48 PM In reply to

    • James Crowley
    • Top 10 Contributor
    • Joined on 12-07-2000
    • United Kingdom
    • Guru
    • Points 15,030
    • SystemAdministrator
    Okay, point taken ... but as far as I'm aware if you moved the code I talk about out of triggers just into stored procs (or whatever), then the SQL is pretty standard stuff?

    I know that you're a very well respected author on this area, and I'm still *very* new to this, but I had difficulty with the fact that it was so relatively "hard" to work out things like who a nodes parent is, and what its depth/level was with your solutions.... am I missing something obvious here? Thanks for your time!
    • Post Points: 0
  • 11-04-2005 5:13 AM In reply to

    • jcelko
    • Not Ranked
    • Joined on 09-22-2005
    • New Member
    • Points 20

    Nestedet model

    Here is my standard "cut & paste" on the Nested sets model for hierarchies.

    There are many ways to represent a tree or hierarchy in SQL.  This is called an adjacency list model and it looks like this:

    CREATE TABLE OrgChart
    (emp CHAR(10) NOT NULL PRIMARY KEY,
     boss CHAR(10) DEFAULT NULL REFERENCES OrgChart(emp),
     salary DECIMAL(6,2) NOT NULL DEFAULT 100.00);

    OrgChart
    emp       boss      salary
    ===========================
    'Albert'  NULL    1000.00
    'Bert'    'Albert'   900.00
    'Chuck'   'Albert'   900.00
    'Donna'   'Chuck'    800.00
    'Eddie'   'Chuck'    700.00
    'Fred'    'Chuck'    600.00

    Another way of representing trees is to show them as nested sets.

    Since SQL is a set oriented language, this is a better model than the usual adjacency list approach you see in most text books. Let us define a simple OrgChart table like this.

    CREATE TABLE OrgChart
    (emp CHAR(10) NOT NULL PRIMARY KEY,
     lft INTEGER NOT NULL UNIQUE CHECK (lft > 0),
     rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
     CONSTRAINT order_okay CHECK (lft < rgt) );

    OrgChart
    emp         lft rgt
    ======================
    'Albert'      1   12
    'Bert'        2    3
    'Chuck'       4   11
    'Donna'       5    6
    'Eddie'       7    8
    'Fred'        9   10

    The organizational chart would look like this as a directed graph:

               Albert (1, 12)
               /        \
             /            \
       Bert (2, 3)    Chuck (4, 11)
                      /    |   \
                    /      |     \
                  /        |       \
                /          |         \
           Donna (5, 6) Eddie (7, 8) Fred (9, 10)

    The adjacency list table is denormalized in several ways. We are modeling both the Personnel and the organizational chart in one table. But for the sake of saving space, pretend that the names are job titles and that we have another table which describes the Personnel that hold those positions.

    Another problem with the adjacency list model is that the boss and employee columns are the same kind of thing (i.e. names of personnel), and therefore should be shown in only one column in a normalized table.  To prove that this is not normalized, assume that "Chuck" changes his name to "Charles"; you have to change his name in both columns and several places. The defining characteristic of a normalized table is that you have one fact, one place, one time.

    The final problem is that the adjacency list model does not model subordination. Authority flows downhill in a hierarchy, but If I fire Chuck, I disconnect all of his subordinates from Albert. There are situations (i.e. water pipes) where this is true, but that is not the expected situation in this case.

    To show a tree as nested sets, replace the nodes with ovals, and then nest subordinate ovals inside each other. The root will be the largest oval and will contain every other node.  The leaf nodes will be the innermost ovals with nothing else inside them and the nesting will show the hierarchical relationship. The (lft, rgt) columns (I cannot use the reserved words LEFT and RIGHT in SQL) are what show the nesting. This is like XML, HTML or parentheses.

    At this point, the boss column is both redundant and denormalized, so it can be dropped. Also, note that the tree structure can be kept in one table and all the information about a node can be put in a second table and they can be joined on employee number for queries.

    To convert the graph into a nested sets model think of a little worm crawling along the tree. The worm starts at the top, the root, makes a complete trip around the tree. When he comes to a node, he puts a number in the cell on the side that he is visiting and increments his counter.  Each node will get two numbers, one of the right side and one for the left. Computer Science majors will recognize this as a modified preorder tree traversal algorithm. Finally, drop the unneeded OrgChart.boss column which used to represent the edges of a graph.

    This has some predictable results that we can use for building queries.  The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM TreeTable)); leaf nodes always have (left + 1 = right); subtrees are defined by the BETWEEN predicate; etc. Here are two common queries which can be used to build others:

    1. An employee and all their Supervisors, no matter how deep the tree.

    SELECT O2.*
      FROM OrgChart AS O1, OrgChart AS O2
     WHERE O1.lft BETWEEN O2.lft AND O2.rgt
       AND O1.emp = :myemployee;

    2. The employee and all their subordinates. There is a nice symmetry here.

    SELECT O1.*
      FROM OrgChart AS O1, OrgChart AS O2
     WHERE O1.lft BETWEEN O2.lft AND O2.rgt
       AND O2.emp = :myemployee;

    3. Add a GROUP BY and aggregate functions to these basic queries and you have hierarchical reports. For example, the total salaries which each employee controls:

    SELECT O2.emp, SUM(S1.salary)
      FROM OrgChart AS O1, OrgChart AS O2,
           Salaries AS S1
     WHERE O1.lft BETWEEN O2.lft AND O2.rgt
       AND O1.emp = S1.emp
     GROUP BY O2.emp;

    4. To find the level of each emp, so you can print the tree as an indented listing.  Technically, you should declare a cursor to go with the ORDER BY clause.

    SELECT COUNT(O2.emp) AS indentation, O1.emp
      FROM OrgChart AS O1, OrgChart AS O2
     WHERE O1.lft BETWEEN O2.lft AND O2.rgt
     GROUP BY O1.lft, O1.emp
     ORDER BY O1.lft;

    5. The nested set model has an implied ordering of siblings which the adjacency list model does not. To insert a new node, G1, under part G.  We can insert one node at a time like this:

    BEGIN ATOMIC
    DECLARE rightmost_spread INTEGER;

    SET rightmost_spread -- can be put into the UPDATE
       = (SELECT rgt
            FROM Frammis
           WHERE part = 'G');
    UPDATE Frammis
      SET lft = CASE WHEN lft > rightmost_spread
                     THEN lft + 2
                     ELSE lft END,
          rgt = CASE WHEN rgt >= rightmost_spread
                     THEN rgt + 2
                     ELSE rgt END
    WHERE rgt >= rightmost_spread;

    INSERT INTO Frammis (part, lft, rgt)
    VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
    COMMIT WORK;
    END;

    The idea is to spread the (lft, rgt) numbers after the youngest child of the parent, G in this case, over by two to make room for the new addition, G1.  This procedure will add the new
    • Post Points: 0
  • 04-24-2006 11:44 AM In reply to

    • Goose99
    • Not Ranked
    • Joined on 04-24-2006
    • United Kingdom
    • New Member
    • Points 10

    Re: [4633] Tree structures in ASP.NET and SQL Server

    Thanks this article has been a great help, I have one question.

    How hard would it be to get the tree from SQL in XML so that you could use ASP.net 2 tree control?

    Regards Geraint

    • Post Points: 10
  • 03-11-2007 2:56 PM In reply to

    • toranaga
    • Not Ranked
    • Joined on 03-11-2007
    • New Member
    • Points 5

    Re: [4633] Tree structures in ASP.NET and SQL Server

    Here is how id did it to use with asp:tree:

    add this methods to the TreeNode class

    public string GetXml
        {
            get
            {
                XmlDocument xDoc = new XmlDocument();
                XmlElement root = (XmlElement) xDoc.AppendChild(xDoc.CreateElement("node"));
                root.SetAttribute("id", this.UniqueID.ToString());
                root.SetAttribute("name", this.Name);
                foreach (TreeNode tn in this.Children)
                {
                    AppendChildren(root, tn);
                }
                return xDoc.OuterXml;
            }
        }

        private void AppendChildren(XmlElement root, TreeNode tn)
        {
            XmlElement node = (XmlElement)root.AppendChild(root.OwnerDocument.CreateElement("node"));
            node.SetAttribute("id", tn.UniqueID.ToString());
            node.SetAttribute("name", tn.Name);
            foreach (TreeNode child in tn.Children)
            {
                AppendChildren(node, child);
            }
        }

    the xml has all the info i need for the tree control, feel free to change it to your needs
    hope this helps

































    • Post Points: 5
Page 2 of 2 (26 items) < Previous 1 2