[转]实现了一个SQL查询整个树状结构数据的方法
转自:游荡的灵魂
表结构是这样的
CalssId 标识id
Sid 上级id (就是上级的标识Id)
填充数据后是这样
CalssId Sid
1 0
2 1
3 1
4 2
4 2
5 3
5 3
这样的表结构在无限分级的系统中应该是广泛应用吧!当你知道某个结点的id而需要查询其结点下所有项怎么办。
我也实在想不到其他的办法,就只有用临时表和Goto来实现;
应该有更好的方法吧,知道的请指教一下,小声告诉我!
这些个代码很简单,不需要解释了吧!
另
表结构是这样的
CalssId 标识id
Sid 上级id (就是上级的标识Id)
填充数据后是这样
CalssId Sid
1 0
2 1
3 1
4 2
4 2
5 3
5 3
这样的表结构在无限分级的系统中应该是广泛应用吧!当你知道某个结点的id而需要查询其结点下所有项怎么办。
我也实在想不到其他的办法,就只有用临时表和Goto来实现;
应该有更好的方法吧,知道的请指教一下,小声告诉我!
这些个代码很简单,不需要解释了吧!
Create TABLE #Temp1 (TempId int)
Create TABLE #Temp2 (TempId int)
Create TABLE #Temp3 (TempId int)
insert into #Temp1 select Classid from Class where sid=@ClassId
Up:
insert into #Temp3 Select TempId from #Temp1
insert into #Temp2 Select Classid from Class where sid in (select Tempid from #Temp1 )
delete #Temp1
insert into #Temp1 Select TempId from #Temp2
delete #Temp2
if @@Rowcount=0
goto ExitUp
goto Up
ExitUp:
drop table #Temp1
drop table #Temp2
Select * from #Temp3
drop table #Temp3
return
Create TABLE #Temp2 (TempId int)
Create TABLE #Temp3 (TempId int)
insert into #Temp1 select Classid from Class where sid=@ClassId
Up:
insert into #Temp3 Select TempId from #Temp1
insert into #Temp2 Select Classid from Class where sid in (select Tempid from #Temp1 )
delete #Temp1
insert into #Temp1 Select TempId from #Temp2
delete #Temp2
if @@Rowcount=0
goto ExitUp
goto Up
ExitUp:
drop table #Temp1
drop table #Temp2
Select * from #Temp3
drop table #Temp3
return
另
WITH ProductsCategoriesCTE(CategoryId, CategoryName, LevelColumn, OrderColumn)
AS
(
SELECT CategoryId, CategoryName, 0 as LevelColumn, CAST(categoryId AS VARBINARY(MAX)) as OrderColumn
FROM system_ProductsCategories
WHERE (CategoryParentId is null)
UNION ALL
SELECT system_ProductsCategories.CategoryId, system_ProductsCategories.CategoryName, ProductsCategoriesCTE.LevelColumn+1,
CAST(OrderColumn + CAST(system_ProductsCategories.CategoryId AS BINARY(4)) AS VARBINARY(MAX))
FROM system_ProductsCategories
JOIN ProductsCategoriesCTE
ON system_ProductsCategories.CategoryParentId = ProductsCategoriesCTE.CategoryId
)
SELECT CategoryId, '├' + REPLICATE('─', LevelColumn) + ' ' + CategoryName as CategoryName
FROM ProductsCategoriesCTE
ORDER BY OrderColumn, CategoryName
AS
(
SELECT CategoryId, CategoryName, 0 as LevelColumn, CAST(categoryId AS VARBINARY(MAX)) as OrderColumn
FROM system_ProductsCategories
WHERE (CategoryParentId is null)
UNION ALL
SELECT system_ProductsCategories.CategoryId, system_ProductsCategories.CategoryName, ProductsCategoriesCTE.LevelColumn+1,
CAST(OrderColumn + CAST(system_ProductsCategories.CategoryId AS BINARY(4)) AS VARBINARY(MAX))
FROM system_ProductsCategories
JOIN ProductsCategoriesCTE
ON system_ProductsCategories.CategoryParentId = ProductsCategoriesCTE.CategoryId
)
SELECT CategoryId, '├' + REPLICATE('─', LevelColumn) + ' ' + CategoryName as CategoryName
FROM ProductsCategoriesCTE
ORDER BY OrderColumn, CategoryName