在SQL的儲存過程中應用游標計算

2021-04-13 05:02:29 字數 1049 閱讀 9063

--建立乙個儲存過程,並返回乙個已經開啟的游標

create procedure return_cursor

(@userid varchar(40),

@cur_kpi_guid cursor varying output)as

begin

set @cur_kpi_guid=cursor local scroll for

select guid from kpi_user where userid=@userid

open  @cur_kpi_guid

end--求和的儲存過程

create  procedure sum_num

(@userid varchar(40))as

declare

@cur_kpi_guid cursor,--游標變數

@kpi_guid varchar(50)

begin

--呼叫上面的儲存過程,得到開啟的游標

execute return_cursor @userid,@cur_kpi_guid output

--取出游標中的第一行資料

fetch  @cur_kpi_guid into @kpi_guid

--迴圈計算每個表的總分

while @@fetch_status=0

begin

select sum(num) from kpi_usernumitem where itemguid

in (select itemguid from kpi_baseitems where guid=@kpi_guid) and

guid=(select guid from kpi_usernum where userid=@userid)

--繼續取資料

fetch  @cur_kpi_guid into @kpi_guid

end--關閉游標

close @cur_kpi_guid

deallocate @cur_kpi_guid

end--執行儲存過程

exec sum_num 1 

儲存過程中使用游標

create proc cursortest id int 0,name varchar 50 as 建立游標 declare cursor cursor 設定游標欲操作的資料集 set cursor cursor for select id,name from users 開啟游標 open cu...

Oracle儲存過程中如何使用游標

本儲存過程的功能 把test tbl2中與test tbl1中id相同但salary不同的記錄中的salary的值更新為test tbl1中的salary的值 建立儲存過程 create or replace procedure p update test tbl2 is 定義游標 cursor c...

通過游標在SQL儲存過程中迴圈

今天有個需求要寫乙個儲存過程,需要從乙個表中讀取資料到另外乙個表中,由於是很多行的資料,所以需要迴圈,我琢磨了一下,使用了游標,至於使用游標的好壞,還請大家指點,先建立兩個測試表吧 create table testa id intidentity userchname nvarchar 50 us...