请高手帮帮忙行嘛!!SQL存储过程难题呀!!!
已知父子关系记录存在于一张表中:
__________________________________________
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
注:级别层数可能会超过100层,注意性能。
------解决方案--------------------根據你的結構改寫的函數
--建立測試環境
Create Table Tree
(id Int,
Parent_id Int,
Name Nvarchar(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 Function GetChildren(@User_id Int)
Returns Int
As
Begin
Declare @Score int
Declare @Tree Table (id Int, Parent_id Int, Name Nvarchar(10))
Insert @Tree Select id, Parent_id, Name From Tree Where Parent_id = @User_id
While @@Rowcount > 0
Insert @Tree Select A.id, A.Parent_id, A.Name From Tree A Inner Join @Tree B On A.Parent_id = B.id And A.id Not In (Select id From @Tree)
Select @Score = Count(*) From @Tree
Return @Score
End
GO
--測試
Select dbo.GetChildren(1) As Score
Select dbo.GetChildren(3) As Score
GO
--刪除測試環境
Drop Table Tree
Drop Function GetChildren
--結果
/*
Score
4
Score
1
*/
------解决方案--------------------create table ta(id int,Parent_id int, Name varchar(5))
insert ta select 1, -1, '张三 '
insert ta select 2, 1, '里斯 '
insert ta select 3, 1, '王武 '
insert ta select 4, 2, '赵六 '
insert ta select 5, 3, '牛七 '
create function test_f(@id int)
returns int
as
begin
declare @i int
set @i=1
declare @ta table(id int,Parent_id int, Name varchar(5),lev int)
insert @ta select *,@i from ta where id=@id
while @@rowcount> 0
begin
set @i=@i+1
insert @ta select ta.*,@i from ta join @ta b on ta.Parent_id=b.id and b.lev=@i-1
end
select @i=count(1) from @ta
return @i-1--改一下只计算下级 <