首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求一条递归的sql语句!解决办法

2012-02-02 
求一条递归的sql语句!表aidparentidstatus10开启20开启31开启43开启54开启64开启定义parentid为0时此节点

求一条递归的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
(idInt,
parentidInt,
statusNvarchar(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
--結果
/*
idparentidstatus
10关闭
20开启
31关闭
43关闭
54关闭
64关闭
*/

热点排行