提示:編寫過程當中,可需參閱聯機叢書獲取下列內容的具體用法sql
一、聲明變量可用declare,爲變量賦值用set數據庫
二、須要判斷可用if語句,如if內需執行多條語句,可用begin 和 end 來限定if做用的範圍c#
三、可經過while循環來依次讀取全部記錄,讀取狀態可用@@FETCH_STATUS獲取函數
四、如遊標已建立,但執行過程當中出錯。致使從新執行時提示遊標已存在,可用cursor_status來檢查是否存在該遊標,如存在,則先deallocatefetch
declare @S# VARCHAR(16); --定義臨時變量 declare @C# VARchar(8); declare @SCORE VARCHAR(4); declare mycursor cursor for --定義遊標 select SC.S#,SC.C#,SC.SCORE FROM dbo.SC open mycursor; --打開遊標 fetch from mycursor into @S#,@C#,@SCORE; WHILE @@FETCH_STATUS =0 --若是上一次操做成功則繼續循環 BEGIN print 'S#: '+@S#+'C#:'+@C#+'SCORE:'+@SCORE fetch from mycursor into @S#,@C#,@SCORE; END 空行是由於成績的數據位空(NULL)
在操做遊標時,須要經過declare先定義幾個須要的臨時變量,spa
declare mycursor cursor for select SC.S#,SC.C#,SC.SCORE FROM dbo.SC 這句話是定義遊標語句。3d
mycursor是遊標的名字,dbo.SC是遊標使用的數據庫表名,SC.S#,SC.C#,SC.SCORE是SC表的屬性。code
建立好遊標以後須要打開遊標 openblog
上面的實驗代碼爲使用遊標語句檢索SC表中的S#,C#,SCORE三個屬性的數據。結果以下圖:get
讀取過程當中刪除S5的選課記錄,並將爲空的成績修改成60分。
代碼以下:
open mycursor; --打開遊標 fetch from mycursor into @S#,@C#,@SCORE; WHILE @@FETCH_STATUS =0 --若是上一次操做成功則繼續循環 BEGIN if(@SCORE is null) update SC set SCORE='60' where current of mycursor if(@S#='s5') delete from SC where current of mycursor print 'S#: '+@S#+'C#:'+@C#+'SCORE:'+@SCORE fetch from mycursor into @S#,@C#,@SCORE; END
結果以下:
declare mycursor scroll cursor for --定義遊標 select SC.S#,SC.C#,SC.SCORE FROM dbo.SC order by S# DESC;
use Work go create procedure getTopResultByTbname --建立函數getTopResultByTbname @number int,@tablename varchar(4) --定義函數中number,tablename屬性 as begin declare @sql varchar(50) set @sql='select top '+ cast(@number as char) + '*from' + @tablename; exec(@sql); end DROP PROCEDURE getTopResultByTbname --釋放函數getTopResultByTbname exec getTopResultByTbname 3,' SC' --查詢SC表前三行
go create function getRankBySnoAndCno --定義方法getRankBySnoAndCno (@s# char(16),@c# char(16)) returns int --定義方法中屬性S#,C# as begin declare @ret int ,@score float if not exists (select *from sc where S#=@s# and C#=@c# ) set @ret=-1 else begin set @score =(select SCORE from sc where S#=@s# and C#=@c# ) --SQL語句 set @ret=(select count(*) from SC where C#=@c# and SCORE>@score)+1 --SQL語句 end return @ret end select dbo.getRankBySnoAndCno('s1','c1') --對SC表中的s1,c1進行檢索