遊標的使用

---使用遊標
---1遊標的定義
--(1)定義
declare cur_MyStudent cursor fast_forword
for select * from MyStudent --基於返回一個結果集
--(2)打開
open cur_MyStudent
--(3)操作
fetch next from cur_MyStudent
while @@fetch_status=0   ---while循環說的是多條記錄的操作
begin
fetch next from cur_MyStudent
end
--(4)關閉
close cur_MyStudent
--(5)釋放
deallocate

 


select * from TblTeacher
select * from TblteacherSalary


------1將老師的工資更新,更新後的金額爲原來的工資+獎金。
----第一,定義兩個變量,來存放TblTeacherSalary表中的tTId和reward
declare @id int
declare @reward money
declare cur_Reward cursor fast_forward
for select tTId,reward from TblTeacherSalary ---基於查詢的數據集

open  cur_Reward
 fetch next from cur_Reward into @id,@reward
 while @@fetch_status=0
 begin
 update TblTeacher set tTSalary=tTSalary+@reward where tTId=@id
 fetch next from cur_Reward into @id,@reward
 end
close cur_Reward
deallocate cur_Reward


--2將獎金中的reward設置爲工資的0.1倍

declare @sid int
declare @salary money
--1定義遊標
declare cur_reward2 cursor fast_forward
for select tTId from TblTeacherSalary
--打開
open cur_reward2
fetch next from cur_reward2 into @SId
while @@fetch_status=0
begin
--set @salary=(select tTSalary from TblTeacher)
select @salary=tTSalary from TblTeacher
--更新獎金錶
update TblTeacherSalary set reward=@salary*0.1 where tTId=@sid
end
close cur_reward2
deallocate cur_reward2

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