求一个函数

yimi_love 2007-11-08 06:28:00
Id ParentID Contain
232 -1 0
234 232 0
235 232 0
237 234 9302
238 236 9302
246 235 6329
247 240 0
248 235 1107
250 236 6329

谁能给我写一个函数:通过id 求出所有id 子类 的Contain的和。
例如:232 的子类是234,235,而234的子类是237,235的子类是246,248
那么232 的子类就是234,235,237,246,248
...全文
157 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2007-11-08
  • 打赏
  • 举报
回复
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

fcuandy 2007-11-08
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20071107/13/948cd8bb-c09c-4e30-9578-b34a910f5928.html

跟这个贴子一样. 只不过这个贴子里取的是层数,是int值累加. 你的这个是varchar值累集相连就可以了

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧