儲存過程中游標的使用

2021-07-17 00:09:55 字數 2244 閱讀 5328

例如:乙個公司,按照如下規則計算加薪金額:

1.公司中除了總裁(president)外,所有人都會至少增加p_min的薪水

2.任何獎金(bonus)高於$600的員工都會另增加4%

3.員工的佣金(commission)越高,增加越少。佣金(commission)少於$2000的另增加3%,佣金(commission)在$2000到$3000的增加另2%

4.佣金(commission)高於$3000的另增加1%

5.無論每個員工增加多少,增加比例不能高於p_max

create procedure total_raise ( in  p_min dec(4,2)

, in  p_max dec(4,2)

, out p_total dec(9,2) )

language sql

specific total_raise      

tr: begin

-- declare variables

declare v_salary dec(9,2);

declare v_bonus  dec(9,2);

declare v_comm   dec(9,2);

declare v_raise  dec(4,2);

declare v_job    varchar(15) default 'pres';

-- declare returncode

declare sqlstate char(5);

-- procedure logic

declare c_emp cursor for

select salary, bonus, comm

from   employee

where  job != v_job;                              -- (1)這裡的select定義了結果集中的行和

列open c_emp;                                        -- (2)

set p_total = 0;

fetch from c_emp into v_salary, v_bonus, v_comm;  -- (3)得到一行資料,並將其

複製給本地變數

while ( sqlstate = '00000' ) do                   --sqlstate 00000: 操作執行成功,

並且未產生任何型別的警告或異常情

況。通過這個可以檢查是否到達最後一行

set v_raise = p_min;

if ( v_bonus >= 600 ) then

set v_raise = v_raise + 0.04;

end if;

if ( v_comm < 2000 ) then

set v_raise = v_raise + 0.03;

elseif ( v_comm < 3000 ) then

set v_raise = v_raise + 0.02;

else

set v_raise = v_raise + 0.01;

end if;

if ( v_raise > p_max ) then

set v_raise = p_max;

end if;

set p_total = p_total + v_salary * v_raise;

fetch from c_emp into v_salary, v_bonus, v_comm;  -- (4)在while邏輯中得到

更多的行資料

end while;

close c_emp;                                          -- (5)

end tr

1、為什麼要在儲存過程中加入游標?
當我要在儲存過程中選出表的多行記錄時,並對這些記錄進行操作時,就要使用游標。
游標本質上是儲存過程中定義的乙個變數。
2、以上的計算規則是怎樣的?
以上的計算規則要確定 優先順序。
第一優先順序,公司中除了總裁(president)外,所有人都會至少增加p_min的薪水。
第二優先順序,2.任何獎金(bonus)高於$600的員工都會另增加4%。

看**的計算順序就可以知道。

儲存過程中的游標使用

利用儲存過程來消除資料庫中冗餘的資料 create procedure sp mytest as declare pro varchar 50 declare mm int declare wu cursor for select distinct product from mytest open ...

Oracle儲存過程中多層巢狀游標的用法

oracle sql指令碼 create or replace procedure p delete qk pid in number,deep in number as pid 分類id deep 深度,層級 one val number two val number three val numb...

sql service 儲存過程,游標的使用

1 建表 drop table dbo.users gocreate table dbo.users id int not null name varchar 32 null go alter table dbo.users add primary key id go2 新增資料 刪除儲存過程 if...