sql存儲是數(shù)據(jù)庫操作過程中比較重要的一個環(huán)節(jié),對于一些初學者來說也是比較抽象難理解的,本文我將通過幾個實例來解析數(shù)據(jù)庫中的sql存儲過程,這樣就將抽象的事物形象化,比較容易理解。
例1:
create proc proc_stu @sname varchar(20), @pwd varchar(20) as select * from ren where sname=@sname and pwd=@pwd go
查看結(jié)果:proc_stu 'admin','admin'
例2:
下面的存儲過程實現(xiàn)用戶驗證的功能,如果不成功,返回0,成功則返回1.
CREATE PROCEDURE VALIDATE @USERNAME CHAR(20),@PASSWORD CHAR(20),@LEGAL BIT OUTPUT AS IF EXISTS(SELECT * FROM REN WHERE SNAME = @USERNAME AND PWD = @PASSWORD) SELECT @LEGAL = 1 ELSE SELECT @LEGAL = 0
在程序中調(diào)用該存儲過程,并根據(jù)@LEGAL參數(shù)的值判斷用戶是否合法。
例3:一個高效的數(shù)據(jù)分頁的存儲過程 可以輕松應付百萬數(shù)據(jù)
CREATE PROCEDURE pageTest --用于翻頁的測試 --需要把排序字段放在第一列 ( @FirstID nvarchar(20)=null, --當前頁面里的第一條記錄的排序字段的值 @LastID nvarchar(20)=null, --當前頁面里的最后一條記錄的排序字段的值 @isNext bit=null, --true 1 :下一頁;false 0:上一頁 @allCount int output, --返回總記錄數(shù) @pageSize int output, --返回一頁的記錄數(shù) @CurPage int --頁號(第幾頁)0:第一頁;-1最后一頁。 ) AS if @CurPage=0--表示第一頁 begin --統(tǒng)計總記錄數(shù) select @allCount=count(ProductId) from Product_test set @pageSize=10 --返回第一頁的數(shù)據(jù) select top 10 ProductId, ProductName, Introduction from Product_test order by ProductId end else if @CurPage=-1--表示最后一頁 select * from (select top 10 ProductId, ProductName, Introduction from Product_test order by ProductId desc ) as aa order by ProductId else begin if @isNext=1 --翻到下一頁 select top 10 ProductId, ProductName, Introduction from Product_test where ProductId > @LastID order by ProductId else --翻到上一頁 select * from (select top 10 ProductId, ProductName, Introduction from Product_test where ProductId @FirstID order by ProductId desc) as bb order by ProductId end
上文中講到的這三個例子都是sql存儲過程比較典型的例子,希望大家好好學習,都能夠?qū)W到大家各自需要的東西。
標簽:濱州 來賓 東營 文山 池州 新鄉(xiāng) 黃山 大同
巨人網(wǎng)絡通訊聲明:本文標題《sql存儲過程幾個簡單例子》,本文關鍵詞 sql,存儲,過程,幾個,簡單,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。