--測試
create table ta ( 項目 varchar ( 20), 上級項目 varchar ( 20), num int )
insert ta
select 'A' , '' , 100 union all
select 'B' , 'A' , 200 union all
select 'C' , 'B' , 300 union all
select 'D' , 'B' , 400 union all
select 'E' , 'C' , 500 union all
select 'F' , 'D' , 600 union all
select 'H' , 'E' , 700 union all
select 'G' , 'F' , 800
-- 如果要顯示上級的項目 :
create function roy_f( @ 項目 varchar ( 20))
returns varchar ( 100)
as
begin
declare @ 上級項目 varchar ( 20)
select @ 上級項目 = 上級項目 from ta where 項目 = @ 項目
return case when @ 上級項目 is null then null
else isnull ( dbo. roy_f( @ 上級項目 )+ '-' , '' )+ @ 項目 end
end
-- 如果顯示各級項目的匯總金額 :
create function roy_f2( @ 項目 varchar ( 20))
returns int
as
begin
declare @tb table ( 項目 varchar ( 20), 上級項目 varchar ( 20), num int , lev int )
declare @i int , @sum int
set @i= 0
insert @tb select *, @i from ta where 項目 = @ 項目
while @@rowcount > 0
begin
set @i= @i+ 1
insert @tb
select a.*, @i
from ta a, @tb b
where b. 項目 = a. 上級項目 and b. lev= @i- 1
end
select @sum= sum ( num) from @tb
return @sum
end
-- 測試 :
select 項目 , 金額 = dbo. roy_f2( 項目 ), 關係 = dbo. roy_f( 項目 ) from ta
/*
項目 金額 關係
-------------------- ----------- ---------------
A 3600 A
B 3500 A-B
C 1500 A-B-C
D 1800 A-B-D
E 1200 A-B-C-E
F 1400 A-B-D-F
H 700 A-B-C-E-H
G 800 A-B-D-F-G
(所影響的行數為 8 行)
*/
-- 用預存程序統計 :
create proc roy_p @ 項目 varchar ( 20)
as
begin
declare @i int
set @i= 0
select *, 級數 = @i into #
from ta where 項目 = @ 項目
while @@rowcount > 0
begin
set @i= @i+ 1
insert #
select ta.*, 級數 = @i
from ta, # b
where ta. 上級項目 = b