sql server 的存儲過程實例

/**********
實現功能,將項目每年的月份中的資金數據累加
使用了三個循環嵌套遊標,可能性能不是很好,主要演示存儲過程的實現
***************/

CREATE  PROCEDURE accumulate
AS
declare @temp varchar(255)
declare @Field int

declare @practice_all int
declare @capatital_all int
declare @temppractice int
declare @tempcapital int

declare @month int
declare @year int

declare prject_cursor cursor for SELECT [projectid] AS projectid FROM v_project_year_month GROUP BY projectid

set @practice_all=0
set @capatital_all=0

open prject_cursor    --打開遊標
fetch next from prject_cursor into @Field
while(@@fetch_status=0)    --循環開始
begin
    declare year_cursor cursor for SELECT [year_yd] FROM v_project_year_month WHERE (projectid = @Field) GROUP BY year_yd
    open year_cursor
    fetch next from year_cursor into @year
    while(@@fetch_status=0)
    begin
        print cast(@year as varchar)+'年'+cast(@Field as varchar)+'============項目'
        declare month_cursor cursor for SELECT [Month_yf],[Month_practice],[Month_capital] FROM v_project_year_month WHERE (year_yd=@year) and (projectid =@Field) ORDER BY Month_yf
        open month_cursor
        fetch next from month_cursor into @month,@temppractice,@tempcapital
        while(@@fetch_status=0)
        begin
            
            set @temp=cast(@month as varchar)
            print '月份--'+@temp
            print '投資:'+cast(@temppractice as varchar)+'資金:'+cast(@tempcapital as varchar)
            set @practice_all=@practice_all+@temppractice
            set @capatital_all=@capatital_all+@tempcapital
            --累計投資
            Exec('update v_project_year_month set Month_practice_total='+@practice_all+' where projectid='+@Field+' and month_yf='+@month+'')
            --累計資金
            Exec('update v_project_year_month set Month_capital_total='+@capatital_all+' where projectid='+@Field+' and month_yf='+@month+'')
            
            print @practice_all
            print @capatital_all
            fetch next from month_cursor into @month,@temppractice,@tempcapital
        end
        close month_cursor    --關閉遊標
        deallocate month_cursor--釋放資源
    fetch next from year_cursor into @year
    end
    close year_cursor    --關閉遊標
    deallocate year_cursor    --釋放資源
fetch next from prject_cursor into @Field --下個prject
set @practice_all=0    --歸零
set @temppractice=0    --歸零
set @capatital_all=0    --歸零
set @tempcapital=0    --歸零
end
close prject_cursor    --關閉遊標
deallocate prject_cursor--釋放資源

GO
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章