遞迴用函數、預存程序實現的效果

來源:互聯網
上載者:User

--測試

 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.