期待!~~
写得不好,纯粹是为了练习CTE
CREATE TABLE tb
(
id int IDENTITY(1,1),
level int,
rootid int,
name nvarchar(20)
);
INSERT INTO tb VALUES(1,0,'水果')
INSERT INTO tb VALUES(2,1,'瓜类')
INSERT INTO tb VALUES(3,2,'西瓜')
INSERT INTO tb VALUES(3,2,'哈密瓜')
INSERT INTO tb VALUES(1,0,'蔬菜')
INSERT INTO tb VALUES(2,5,'小白菜')
INSERT INTO tb VALUES(3,2,'香瓜')
;
DECLARE @tn nvarchar(20),@str nvarchar(4000)
SET @str = ''
SET @tn=N'水果'
;WITH
TBS
AS
(
SELECT id,name,level FROM tb WHERE name=@tn
UNION ALL
SELECT a.id,a.name,a.level FROM tb a,TBS b
WHERE a.rootid=b.id
)
SELECT @str = @str+'/'+name FROM TBS WHERE level=1 or level=2
SET @str = right(@str , len(@str) - 1);
WITH
TBS
AS
(
SELECT id,name,level FROM tb WHERE name=@tn
UNION ALL
SELECT A.id,A.name,A.level FROM tb A,TBS B
WHERE a.rootid=b.id
)
SELECT id,(@str+'/'+name) name FROM TBS WHERE level=3
;
DROP TABLE tb
[[it] 本帖最后由 球球 于 2008-10-11 03:36 编辑 [/it]]