日期:2014-05-19  浏览次数:20588 次

求一条递归的sql语句!
表a
id     parentid   status
1           0               开启
2           0               开启
3           1               开启
4           3               开启
5           4               开启
6           4               开启
定义parentid   为0时此节点为根节点,我想做到:假设节点id=1的状态改为关闭,他的所有孩子(节点3,4,5,6)的状态都改为关闭,即输入一个父节点,修改包括他的所有孩子节点状态为“关闭”,谢了!


输入:节点1
输出:
id     parentid   status
1           0               关闭
2           0               开启
3           1               关闭
4           3               关闭
5           4               关闭
6           4               关闭

------解决方案--------------------
--建立測試環境
Create Table a
(id Int,
parentid Int,
status Nvarchar(10))
Insert a Select 1, 0, N '开启 '
Union All Select 2, 0, N '开启 '
Union All Select 3, 1, N '开启 '
Union All Select 4, 3, N '开启 '
Union All Select 5, 4, N '开启 '
Union All Select 6, 4, N '开启 '
GO
--建立函數
Create Function GetChildren(@id Int)
Returns @Tree Table (id Int, parentid Int)
As
Begin
Insert @Tree Select id, parentid From a Where id = @id
While @@Rowcount > 0
Insert @Tree Select A.id, A.parentid From A Inner Join @Tree B On A.parentid = B.id And A.id Not In (Select id From @Tree)
Return
End
GO
--測試
Update a Set status = N '关闭 ' Where id In (Select id From dbo.GetChildren(1))

Select * From a
GO
--刪除測試環境
Drop Table a
Drop Function GetChildren
--結果
/*
id parentid status
1 0 关闭
2 0 开启
3 1 关闭
4 3 关闭
5 4 关闭
6 4 关闭
*/