常用递归结构数据表,返会指点节点,跟其子节点的操作
内容来自机械工业出版的仓库管理系统设计一书
表结构{WareHouserID , ParentWarehouseID }
查询指定节点跟其子节点的信息
ALTER FUNCTION dbo.GetWareSubtreeInfo(@WareHouseID int)
RETURNS @treeinfo table
(
[WareHouseID] [int] NOT NULL,
[ParentWarehouseID] [int] NOT NULL,
[Level] [int] NOT NULL
) AS
BEGIN
--返回所有仓库,不按层次
IF @WareHouseID=0
BEGIN
INSERT INTO @treeinfo
SELECT WareHouseID,0,0 From [WareHouses]
RETURN
END
DECLARE @level AS int
SELECT @level = 0
INSERT INTO @treeinfo
SELECT WareHouseID, ParentWarehouseID, @level
From [WareHouses]
WHERE [WareHouseID] = @WareHouseID
----每次循环是@level会加1,这样做Join 连接时会不断的将子类,以及子来的子类逐步添加到临时表 里
WHILE @@ROWCOUNT > 0
BEGIN
SET @level = @level + 1
INSERT INTO @treeinfo
SELECT D.WareHouseID, D.ParentWarehouseID, @level
From [WareHouses] As D
JOIN @treeinfo AS T
ON D.[ParentWarehouseID] = T.[WareHouseID] AND T.[Level] = @level - 1
END
RETURN
END