I have a table structure like below :
categoryID bigint , primary key , not null
categoryName nvarchar(100)
parentID bigint, not null
where as categoryID and parentID has an one-to-many relation to each other
and I want to create a nested categories with unlimited depth out of this table in my program.
I have a solution but it is not work so good and only returns the root please see the code :
private static string createlist(string catid, string parent)
{
string sql = "SELECT categoryID , categoryName FROM category WHERE parentID = " + parent;
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=sanjab;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
if (catid != "")
catid += ", ";
catid += sdr[1].ToString();
createlist(catid, sdr[0].ToString());
}
return catid;
}
although the code is not very efficient cause it is opening a lots of connection at the same time but with the help of above code and little bit of tweaking I can manage 2-levels depth categories but more than that means lots of trouble for me.
is there any easier method or algorithm?
regards.
Nested Sets are one well-regarded solution for the SQL end of this equation. It requires a bit more application logic, so you’ll want to abstract out the behavior to the extent that you can.
They have some limitations if the elements have frequent inserts or deletes, but that shouldn’t apply in your case. The solution when you do have frequent inserts or deletes is usually to create numbering gaps among the children.
http://www.sqlteam.com/article/more-trees-hierarchies-in-sql has references to an early Celko article on the topic, and some contemporary variations on the theme.