遊標的建立

 

--使用遊標
--遊標的定義
--(1)定義
declare cur_student cursor fast_forward--遊標快速向前
for select * from student--基於返回的結果集
--2(打開)
open cur_student
--3操作
fetch next from cur_student--向下移動一條遊標
while @@fetch_status=0--=0標誌着上次遊標移動成功
begin
fetch next from cur_student
end
--4關閉
close cur_student
--5釋放遊標
deallocate cur_student

 

 

 

use testschool

create table tblsealare (tTid int, tTname nvarchar(50),tTsalaryjj money)
insert into tblsealare
select 1,'姚洪波',200 union all
select 2,'李偉',100 union all
select 3,'陳偉華',400 union all
select 4,'陳紅軍',300

select * from TblTeacher
select * from tblsealare
declare @salary int
declare @sid int
declare cur_reward2 cursor forward_only
for select tTid from tblsealare--獎金錶
--打開
open cur_reward2
--操作
fetch next from cur_reward2 into @sid--獎金錶sid
while @@FETCH_STATUS=0
begin
select @salary= tTsalary from TblTeacher where tTid=@sid
--更新獎金錶
update tblsealare set tTsalaryjj=@salary*0.1 where CURRENT of cur_reward2
fetch next from cur_reward2 into @sid
end
close cur_reward2
--5釋放遊標
deallocate cur_reward2
----------------------------------------------
-------------------------將工資更新,更新後的金額爲原來的工資+獎金
declare @s1 int
declare @id int
declare cur_jj cursor forward_only
for select tTid from TblTeacher--工資表
open cur_jj
fetch next from cur_jj into @id--工資表id獲取
while @@FETCH_STATUS=0
begin
select @s1= tTsalaryjj from tblsealare where tTid =@id
update TblTeacher set  tTsalary =tTsalary+@s1 where CURRENT of cur_jj
fetch next from cur_jj into @id
end
close cur_jj
deallocate cur_jj
--3把遊標寫在對面的表上第一題把遊標寫在TblTeacher.改TblTeacher;--第二題改TblTeacherSalary,我們把遊標寫在techar上。
declare @s2 int
declare @id2 int
declare cur_jj2 cursor forward_only
for select tTid from tblsealare
open cur_jj2
fetch next from cur_jj2 into @id2
while @@FETCH_STATUS=0
begin
select @s2= tTsalaryjj from tblsealare where tTid=@id2
update TblTeacher set tTsalary=tTsalary+@s2 where tTid=@id2
fetch next from cur_jj2 into @id2
end
close cur_jj2
deallocate cur_jj2
--4把獎金錶中的獎金更新爲 reward-teacher.salary*0.05
declare @id3 int
declare @sa int
declare cur_jj3 cursor forward_only
for select tTid from tblsealare
open cur_jj3
fetch next from cur_jj3 into @id3
while @@FETCH_STATUS=0
begin
select @sa= tTsalary from TblTeacher where tTid=@id3
set @sa=@sa*0.05
update tblsealare set tTsalaryjj=tTsalaryjj-@sa where tTid=@id3
fetch next from cur_jj3 into @id3
end
close cur_jj3
deallocate cur_jj3

ps:不要忘記關閉和釋放遊標

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