34,837
社区成员




create table T(Id int, ParentID int, Contain int)
insert T select 232, -1, 0
insert T select 234, 232, 0
insert T select 235, 232, 0
insert T select 237, 234, 9302
insert T select 238, 236, 9302
insert T select 246, 235, 6329
insert T select 247, 240, 0
insert T select 248, 235, 1107
insert T select 250, 236, 6329
go
create function Test_f(@ID int)
returns int
as
begin
declare @sum int
declare @T table(ID int,ParentID int,Contain int,lev int)
insert @T select *,@ID from T where ID=@ID
while @@rowcount>0
begin
set @ID=@ID+1
insert @T select t.*,@ID from T join @T T2 on t.ParentID=t2.ID and t2.Lev=@ID-1
end
select @sum=sum(Contain) from @T
return @sum
end
go
select *,[合计]=dbo.Test_f(ID) from T
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
Id ParentID Contain 合计
----------- ----------- ----------- -----------
232 -1 0 16738
234 232 0 9302
235 232 0 7436
237 234 9302 9302
238 236 9302 9302
246 235 6329 6329
247 240 0 0
248 235 1107 1107
250 236 6329 6329
(所影响的行数为 9 行)
--drop function Test_f
--drop table T