码迷,mamicode.com
首页 > 其他好文 > 详细

创建自定义存储过程

时间:2015-03-19 23:45:14      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

--创建自定义存储过程
--语法:
--if exists(select * from sysobjects where name=‘‘)
-- drop proc ‘‘
--go
--create proc[edure] usp_名称
-- 相当于方法的():创建参数
--as
-- 相当于方法{}:方法体
--go
--调用语法:
--exec 存储过程名称 参数值,参数值 。。。。。
--创建存储过程,获取所有学员信息
if exists(select * from sysobjects where name=‘usp_getStuInfo‘)
drop proc usp_getStuInfo
go
create proc usp_getStuInfo
--参数区域
as
--方法体
select * from Student
go
--调用存储过程,获取所有学员信息
exec usp_getStuInfo

exec sp_executesql N‘usp_getStuInfo‘

--获取指定性别的学员信息
go
if exists(select * from sysobjects where name=‘usp_getStuInfoBySex‘)
drop proc usp_getStuInfoBySex
go
create proc usp_getStuInfoBySex
--参数列表区域
@sex char(2) --声明参数不能使用declare
as
select * from Student where Sex=@sex
go
--调用存储过程,获取指定性别的学员信息
exec usp_getStuInfoBySex ‘男‘
--创建存储过程,获取指定班级和性别的学员信息
go
if exists(select * from sysobjects where name=‘usp_getStuInfoBySexandcid‘)
drop proc usp_getStuInfoBySexandcid
go
create proc usp_getStuInfoBySexandcid
@sex char(2)=‘男‘ , --多个参数之间使用,分隔 输入参数(调用的时候必须传入值,及参数的默认值,用户可以选择是否传入值) 性别 ,参数有默认值 一般会建议有默认值的参数会创建在参数列表 的最后
@className nvarchar(50) --最后一个参数不需要使用, 班级名称
as
declare @cid int --班级ID
set @cid=(select classid from Classes where classname=@className) --获取班级ID
select * from Student where Sex=@sex and ClassId=@cid
go
--调用存储过程,获取指定性别和班级的学员信息
--一旦使用了 ‘@name = value‘ 形式之后,所有后续的参数就必须以 ‘@name = value‘ 的形式传递。
exec usp_getStuInfoBySexandcid default,@className=‘七期班‘

--创建存储过程,获取指定班级和性别的总人数及信息
go
if exists(select * from sysobjects where name=‘usp_getStuNumBySexandcid‘)
drop proc usp_getStuNumBySexandcid
go
create proc usp_getStuNumBySexandcid
@num int output, --满足条件的总记录数 output:标记这个参数是需要输出的,意味着他会向服务器请求返回这个参数的值
@totalnum int output, --总人数 不要为输出参数赋值默认值,没有意义
@classname nvarchar(50),--班级名称
@sex char(2)=‘男‘--性别
as
declare @cid int =(select classid from Classes where classname=@classname)
select * from Student where ClassId=@cid and Sex=@sex--返回结果集
select @num=COUNT(*) from Student where ClassId=@cid and Sex=@sex --计算满足条件的记录数.如果在存储过程中没有重新赋值, 那么就会返回null值
select @totalnum=(select COUNT(*) from Student)
return 100
go
--调用存储过程,获取指定班级和性别的总人数
declare @cnt int=100,@tnum int --接收从服务器返回的output参数值
exec usp_getStuNumBySexandcid @cnt output,@tnum output,‘七期班‘ --output发送请求
select @cnt,@tnum

--返回值---return
if exists(select * from sysobjects where name=‘usp_returnValue‘)
drop proc usp_returnValue
go
create proc usp_returnValue
@sid int --学号
as

declare @cnt int
exec usp_getStuInfo
--set @cnt=(select COUNT(*) from Student)
Declare @name nvarchar(50)=(select StudentName from Student where StudentNo=@sid)
return @name --只能返回整数值
go

declare @num nvarchar(50)
exec @num= usp_returnValue 10
print @num

create proc usp_getClassesInfo
as
select * from classes
go

 

创建自定义存储过程

标签:

原文地址:http://www.cnblogs.com/dianshen520/p/4352025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!