表:
CREATE TABLE Category(
ID INT,
NAME INT,
ParentID INT
)
向上遞迴:
代碼
CREATE FUNCTION [dbo].[GetRootCategoryID]
/*
Author:yanghh
Date:2009-08-10
des:得到某一類根結點
*/
(
@CategoryID INT
)
RETURNS @SubCategory TABLE(CategoryID INT,Level INT)
AS
BEGIN
DECLARE @level INT
SET @level = 0
INSERT INTO @SubCategory
SELECT ID,@level FROM Category WHERE ID=@CategoryID
WHILE @@ROWCOUNT >0
BEGIN
SET @level = @level+1
INSERT INTO @SubCategory
SELECT ParentId,@level FROM Category A, @SubCategory B
WHERE B.CategoryID = A.ID AND B.Level=@level-1
END
RETURN
END
向下遞迴:
代碼
CREATE FUNCTION [dbo].[GetChildCategoryID]
/*
Author:yanghh
Date:2009-08-10
des:得到某一類別子結點
*/
(
@CategoryID INT
)
RETURNS @SubCategory TABLE(CategoryID INT,Level INT)
AS
BEGIN
DECLARE @level INT
SET @level = 0
INSERT INTO @SubCategory
SELECT ID,@level FROM CC_VOD_FilmCategory WHERE ID=@CategoryID
WHILE @@ROWCOUNT >0
BEGIN
SET @level = @level+1
INSERT INTO @SubCategory
SELECT ParentId,@level FROM Category A, @SubCategory B
WHERE B.CategoryID = A.ParentID AND B.Level=@level-1
END
RETURN
END