SQL 中的存储过程:
1.在建立存储过程之前检查所命名的存储过程是否应经存在。(因为如果同名存储过程已经存在,新的存储过程将不被建立)
if exists(select * from sysobject where name='proc name' and type='p')
drop proc proc name
go
2.定义存储过程
create proc test
@gradel int, --定义变量
@gradeh int output --定义输出变量
as
...
go
3.执行存储过程
declare @l int,@h int
exec proc test 34,@h output
print @h
----------------------------------------------
下面以一个例子说明:
输入两个分数,要求写两个存储过程,一个对输入分数排序,另一个查询两分数段之间的成绩:
一共有三个表:
s表:(s#:学生号,sname:学生姓名,age:年龄,sex:性别)
c表:(c#:课程号,cname:课程名,teacher:老师)
sc表:(s#,c#,grade)
if exists(select * from sysobjects where name='sort'
and type='p')
drop proc sort
go --定义一个存储过程用于排序
create proc sort
@high int,
@low int,--定义两个输入参数
@hi int output,
@lo int output--定义两个输出参数
as
if @high<@low
begin
set @high=@high+@low
set @low=@high-@low
set @high=@high-@low
set @hi=@high
set @lo=@low
end
go --如果未按顺序输入则排序
if exists(select * from sysobjects where name='search' and type='p')
drop proc search
go --定义一个存储过程用于查找相应范围的记录
create proc search
@gradeh int,
@gradel int
as
select * from sc where grade between @gradel and @gradeh
if @@rowcount=0
print '查询失败'
go
declare @h int,@l int
exec testpro 70,90,@h output,@l output
exec search @h,@l