【发布时间】:2010-08-12 00:35:56
【问题描述】:
我有一个如下表结构:
categoryID bigint , primary key , not null
categoryName nvarchar(100)
parentID bigint, not null
categoryID 和 parentID 是一对多的关系
我想在我的程序中创建一个无限深度的嵌套类别。
我有一个解决方案,但效果不太好,只返回根请看代码:
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;
}
虽然代码效率不高,因为它同时打开了很多连接,但是借助上面的代码和一点点调整,我可以管理 2 级深度类别,但除此之外意味着很多麻烦对我来说。
有没有更简单的方法或算法?
问候。
【问题讨论】:
-
为什么需要这种类型的解决方案?你需要它的场景是什么?
-
我也会重新标记 sql。我认为您正在寻找一种方法来编写一个查询,该查询在单个查询中返回所有子项,无论深度如何。
-
我做过这种事情,使用 xsl,但在那种情况下,这是因为我想要 html 作为最终结果。因此,根据您的需求,这可能值得探索。 (您可能想尝试在搜索词中包含“层次结构”)。