读书人

高手高手快进来帮帮忙

发布时间: 2012-01-13 22:43:29 作者: rapoo

高手高手快进来帮帮忙.在线等
已知父子关系记录存在于一张表中:
__________________________________________
id | Parent_id | Name
------------------------------------------
1 | -1 | 张三
------------------------------------------
2 | 1 | 里斯
------------------------------------------
3 | 1 | 王武
------------------------------------------
4 | 2 | 赵六
------------------------------------------
5 | 3 | 牛七
------------------------------------------
.......

用一个存储过程,计算出某用户下级共有多少子记录

P_GetUsersScore @User_id bigint, @Score int output
AS
.....
.....
set @Score = xxxx
GO

[解决办法]
--建立境
Create Table Tree
(idbigint,
Parent_idbigint,
NameNvarchar(10))
Insert Tree Select 1, -1, N '张三 '
Union All Select 2, 1, N '里斯 '
Union All Select 3, 1, N '王武 '
Union All Select 4, 2, N '赵六 '
Union All Select 5, 3, N '牛七 '
GO
--建立存程
Create Procedure P_GetUsersScore @User_id bigint, @Score int output
AS
Select * Into #T From Tree Where id = @User_id
While @@ROWCOUNT > 0
Insert #T Select A.* From Tree A Inner Join #T B On A.Parent_id = B.id Where A.id Not In (Select Distinct id From #T)
Select @Score = Count(*) - 1 From #T
Drop Table #T
GO
--
Declare @Score int
EXEC P_GetUsersScore 1, @Score output
Select @Score As Score
EXEC P_GetUsersScore 2, @Score output
Select @Score As Score
GO
--除境
Drop Table Tree
Drop Procedure P_GetUsersScore
--果
/*
Score
4

Score
1
*/

读书人网 >SQL Server

热点推荐