sql存儲過程幾個簡單例子
發(fā)布日期:2021-12-20 22:46 | 文章來源:站長之家
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
查看結果: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
在程序中調用該存儲過程,并根據(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存儲過程比較典型的例子,希望大家好好學習,都能夠學到大家各自需要的東西。
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯(lián)網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
相關文章