存储过程的入门使用的总结
存储过程的基本知识,请先查询百度。
一、创建存储过程:
1、无返回值的
(1)又无参数的
create proc myproc1
as
select * from StudentInfo;
select name from StudentInfo where name like '李%';
(2)有一个参数的
create proc myproc2
@stusex nchar(10)
as
begin
select name from StudentInfo wheresex=@stusex;
end
(3)有多个参数的
create proc myproc3
@stusex nchar(10),
@stuage int,
@stuenglish int
as
begin
select name,age,english from StudentInfo wheresex=@stusex and
age<@stuage and english>@stuenglish;
end
2、带返回值的
(1)通过output返回的
A、有1个返回值的
create proc myproc4
@stusex nchar(10),
@avgenglish int output
as
begin
select @avgenglish= avg(english) from StudentInfo wheresex=@stusex;
end
B、有多个返回值的
create proc myproc5
@stusex nchar(10),
@avgenglish int output,
@maxage int output
as
begin
select @avgenglish= avg(english) from StudentInfo wheresex=@stusex;
select @maxage=max(age) from StudentInfo;
end
(2)通过return返回的
create proc myproc6
@stusex nchar(10)
as
begin
declare @maxage int
declare @minage int
select @maxage=max(age), @minage=min(age) from StudentInfo where
sex=@stusex;
return @maxage-@minage
end
3、设置参数默认值的
create proc myproc7
@stusex nchar(10)='男'
as
begin
if @stusex<>'男'
set @stusex='男'
select name from StudentInfo wheresex=@stusex;
end
二、执行存储过程:
1、
exec myproc1
2、
exec myproc2 '男'
3、
exec myproc3 '男',16,85
4、
declare @avgenglish int
exec myproc4 '男',@avgenglish
select @avgenglish as '男生的平均英语成绩';
5、
declare @avgenglish int
declare @maxage int
exec myproc5 '女',@avgenglish,@maxage
select @avgenglish as '女生的平均英语成绩',@maxage as '女生的最多年龄';
6、
declare @aged int
exec @aged=myproc6 '女'
select @aged --女生的最大年龄与最小年龄差
7、
exec myproc7
或
exec myproc7 '女'
三、修改存储过程:
alter proc myproc1
as
select name from StudentInfo where name like '李%' and sex='男';
四、查询存储过程是否存在:
declare @str nchar(10)
if exists(select * from sysobjexts where name='myproc1')
begin
set @str='yes'
select @str;
end
else
begin
set @str='no'
select @str;
end
五、删除存储过程:
drop proc myproc1