第六章 存储过程
存储过程:
定义:存储过程是一组预编译的sql语句,它可以包含数据操纵语句,变量,逻辑控制语句等(游标也可以)
存储过程允许带参数,参数分为:
输入参数:可以在调用时向存储过程传递参数,此类参数可用来向存储过程中传入值
输出参数 :从存储过程中返回(输出)值,后面跟随output关键字。(其中参数可以有默认值)
优点:允许模块化程序设计,执行速度更快,减少网络流通量,提高系统安全性
分类:系统存储过程 :有系统定义,存放在master数据库中,类似c#中的系统函数,系统存储过程的名称都已“sp_开头或xp_”开头 (sp_开头:用来进行系统的各项设定;xp_开头:用来调用操作系统提供的功能)
用户自定义存储过程:有用户在自己的数据库中创建的存储过程,类似c#中的用户自定义函数
语法:
--创建存储过程
--语法:
--create proc 存储过程名称
--[{@参数 数据类型}[@参数=默认值] [output]
--](注:[]里面内容可有可无)
--as
--sql语句
--go
--调用:exec 存储过程名称
注:和c#的函数一样 参数可选;参数分为输入参数,输出参数;输入参数允许有默认值
例:获取学生信息
create proc str_student
as
select StuInfo.stuid,stuName,stusex,[subject],score from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid
go
exec str_student
删除语法:
if exists (select *from sys.procedures where name='存储过程名')
drop proc 存储过程名
go
带参数的存储过程:
--查找张三的信息
create proc str_student
(@name varchar(10))
as
select StuInfo.stuid,stuName,stusex,[subject],score from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid and [email protected]
go
exec str_student '张三'
go
输出参数的存储过程:
--查找男生女生各有多少人
create proc str_count
(@boy int output,@girl int output)
as
select @boy=COUNT(*) from StuInfo where stusex='男'
select @girl=COUNT(*) from StuInfo where stusex='女'
go
declare @boy int,@girl int
exec str_count @boy output,@girl output
print '男'+convert(varchar(1),@boy)+'女'+convert(varchar(1),@girl)
go
创建带有默认值得输入参数:
create proc str_student
(@name varchar(10)='张三')
as
select StuInfo.stuid,stuName,stusex,[subject],score from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid and [email protected]
go
exec str_student '李四'
go
创建参数有默认值查询带有默认值的结果没有默认值查询全部结果的存储过程:
create proc str_student
(@name varchar(10)=null)
as
if ( @name is null)
begin
select StuInfo.stuid,stuName,stusex,[subject],score from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid
end
else
begin
select StuInfo.stuid,stuName,stusex,[subject],score from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid and [email protected]
end
go
exec str_student '李四'
go
错误返回机制:
关键字:raiserror
语法:
用RAISERROR语句抛出错误信息--*/
--RAISERROR (错误消息, 严重级别, 状态)
--自定义错误
例:
create proc cuowu
(@num int output,@num1 int output,@num2 int output)
as
if(@num1=0)
begin
raiserror ('不能被0整除',10,2)
set @num2=0
end
else
begin
set @[email protected]/@num1
end
go
declare @c int
exec cuowu 3,3,@c output
print @c