--建立一个数据表 这可以是你的一个物理表
declare @temp table(
ID varchar(20),
ParentID varchar(20),
Name nvarchar(100))
insert into @temp values('A','','分类A')
insert into @temp values('B','','分类B')
insert into @temp values('C','','分类C')
insert into @temp values('D','','分类D')
insert into @temp values('A1','A','分类A1')
insert into @temp values('A2','A','分类A2')
insert into @temp values('A11','A1','分类A11')
insert into @temp values('A12','A1','分类A12')
select * from @temp
--查询"分类A"下面的所有数据
declare @$result table(
ID varchar(20),
ParentID varchar(20),
Name nvarchar(100),
myLevel int)
declare @Level int
set @Level = 0
insert into @$result select *,@Level from @temp where ID='A'
while(@@rowcount>0)
begin
set @Level = @Level + 1
insert into @$result
select a.*,@Level
from @temp a,@$result b
where a.ParentID = b.ID and myLevel = @Level-1
end
select * from @$result
关键就是设一个标志Level进行轮询查找出想要的数据。
查询分类表字段修改成如下:
cataid,catatitle,parentid,orderid
DECLARE @ProductCenterCatalogID int
SET @ProductCenterCatalogID=2;
WITH ACTE(cataid,catatitle,orderid,parentid)
AS
(
SELECT cataid,catatitle,orderid,parentid
FROM cata WHERE cataid=@ProductCenterCatalogID
UNION ALL
SELECT TA.cataid,TA.catatitle,TA.orderid,TA.parentid
FROM cata TA INNER JOIN ACTE TB
ON TA.parentid=TB.cataid
)
SELECT cataid,catatitle,orderid,parentid FROM ACTE order by parentid,orderid