存儲過程的建立與使用

1.基本的存儲過程服務器

(1).查詢全部學員的信息
if exists(select * from sysobjects where name='usp_getAllstudent')
drop proc usp_getAllstudent
go
create procedure usp_getAllstudent--建立存儲過程
as
select * from student
go
--調用存儲過程
exec usp_getAllstudent
2.帶參數的存儲過程
(1).查詢指定性別的學員信息
if exists(select * from sysobjects where name='usp_getAllstudentBySex')
drop proc usp_getAllstudentBySex
go
create procedure usp_getAllstudentBySex
@sex char(2)--形參只是聲明,不是定義,因此不須要declare
as
select * from student where sex = @sex
go
--調用存儲過程
exec usp_getAllstudentBySex '男'ci

(2).查詢指定性別和班級名稱的學員信息
if exists(select * from sysobjects where name='usp_getAllstudentByClassName')
drop proc usp_getAllstudentByClassName
go
create procedure usp_getAllstudentByClassName
@sex char(2),
@className nvarchar(50)
as
declare @ClassId int --科目的ID
set @ClassId = (select classid from grade where classname =@className )
select * from student where sex = @sex and ClassId=@ClassId
go
--調用存儲過程,返回指定班級名稱和性別信息
exec usp_getAllstudentByClassName '男','一班'get

 

3.建立有默認值的存儲過程class

(1).查詢男性別和班級名稱的學員信息
if exists(select * from sysobjects where name='usp_getAllstudentByClassName')
drop proc usp_getAllstudentByClassName
go
create procedure usp_getAllstudentByClassName
@sex char(2)='男',
@className nvarchar(50)
as
declare @ClassId int --科目的ID
set @ClassId = (select classid from grade where classname =@className )
select * from student where sex = @sex and ClassId=@ClassId
go
--調用存儲過程,返回指定班級名稱和性別信息
--參數傳遞順序一致:第一個實參默認就是傳遞第一個形參。。依次略推
--若是有默認值,那麼能夠使用default,或者將有默認值的參數寫在因此參數列表的最後,也能夠使用 參數=值的方法調用存儲過程,這樣就和順序沒有關係了,一旦使用了'@name = value' 形式以後,全部後續的參數就必須以'@name = value' 的形式傳遞
exec usp_getAllstudentByClassName default '一班'變量

 

4.建立帶有輸出參數的存儲過程(返回多個值)object

(1).根據班級和性別查詢學員,同時返回總人數和指定性別的人數
if exists(select * from sysobjects where name='usp_getAllstudentAndCount')
drop proc usp_getAllstudentAndCount
go
create procedure usp_getAllstudentAndCount
@totalNum int output, --若是一個參數添加了output,那麼說明:它是一個輸出參數。代表outout說明了你向服務器請求返回這個參數的值
@classNum int output, --指定班級和性別的總人數
@className nvarchar(50),--輸入參數:須要用戶傳入值
@sex char(2)='男'
as
declare @cid = (select classid from grade where classname =@className )--根據班級名稱獲取班級ID
set @classNum =( select * from student where sex = @sex and ClassId=@ClassId)
set @totalNum =(select count(*) from student)--總人數
go
--調用在輸出參數的存儲過程
--服務器向你返回值,用戶就須要建立對應的變量就受
--標明output 說明你會向服務器請求返回這個參數的值。而服務器也知道了標識output參數在之後須要返回
declare @tnum int,@cnum int
exec usp_getAllstudentByClassName @tnum output, @cnum output, '一班'
print @tnum
print @cnum select

5.建立有返回值的存儲過程(返回一個值)
(1)返回指定人數
if exists(select * from sysobjects where name='usp_getStudentNameByNId')
drop proc usp_getStudentNameByNId
go
create procedure usp_getStudentNameByNId
@cid int
as
declare @name nvarchar(50)
set @cnt=( select count(*) from student where classId= @cid )
--return 只能返回整數值
return @cnt
go
--調用存儲過程,返回指定學號的學員姓名
declare @count int
exec @count = usp_getStudentNameByNId 10
print @count 請求

相關文章
相關標籤/搜索