Sql server 2000與2005 遞歸查詢方式
來源:程序員人生 發布時間:2014-01-09 19:02:47 閱讀次數:2985次
1.sql server 2000 遞歸方式(sql server 2005 通用)
CREATE TABLE tb(ID char(3),PID char(3),Name nvarchar(10))
INSERT tb SELECT '001',NULL ,'山東省'
UNION ALL SELECT '002','001','煙臺市'
UNION ALL SELECT '004','002','招遠市'
UNION ALL SELECT '003','001','青島市'
UNION ALL SELECT '005',NULL ,'四會市'
UNION ALL SELECT '006','005','清遠市'
UNION ALL SELECT '007','006','小分市'
GO
--查詢指定節點及其所有子節點的函數
CREATE FUNCTION f_Cid(@ID char(3))
RETURNS @t_Level TABLE(ID char(3),Level int)
AS
BEGIN
DECLARE @Level int
SET @Level=1
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.ID,@Level
FROM tb a,@t_Level b
WHERE a.PID=b.ID
AND b.Level=@Level-1
END
RETURN
END
GO
--調用函數查詢002及其所有子節點
SELECT a.*
FROM tb a,f_Cid('002') b
WHERE a.ID=b.ID
/*--結果
ID PID Name
------ ------- ----------
002 001 煙臺市
004 002 招遠市
2.sql server 2005(sql server 2000 不能通用):
with ColumnCTE ( id,fatherid)
as
(
select id, fatherid from columninfo where id = xxx
union all
select tt.id,tt.fatherid from columninfo tt join ColumnCTE cte on tt.fatherid = cte.id
)
select * from ColumnCTE