SQL Server数据库开发(6.存储过程)

一、存储过程(procedure)

1.定义:用来执行管理业务或应用复杂的业务规则

存储过程可以带参数,也可以返回结果。

2.存储过程可以包含数据操纵语句、变量、逻辑控制语句

3.存储过程的优点:

3.1允许模块化程序设计

一次创建多次使用,并可独立于源代码而单独修改

3.2执行速度更快

已经通过语法检查和性能优化,存储在服务器,在执行时无需每次编译

3.3减少网络流通量

一个需要百行T-SQL代码的操作可以由一条存储过程单独实现

3.4提高系统安全性

存储过程的定义文本可以被加密,使用户不能查看其内容

可将存储过程座位用户存取数据的管理,取代原有数据表操作

4.存储过程的分类

4.1系统存储过程

由系统定义,存放在master数据库中

类似c#中的系统函数

系统存储过程的名称都可以“sp_”开头或“xp_“开头

“sp_”开头:用来进行系统的各项设定

“xp_“开头:用来调用操作系统提供的功能

4.2用户自定义存储过程

由用户子啊自己的数据库中创建的存储过程

类似c#中的用户自定义函数

--存储过程
IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stu_marks

--go  无参数
--create proc pr_stu_marks
--as
-- select StuInfo.stuid,stuName,subject,score
-- from StuInfo,StuMarks
-- where StuInfo.stuid=StuMarks.stuid
--go
--exec pr_stu_marks

--有参数
create proc pr_stu_marks(@name char(10))
as
 select StuInfo.stuid,stuName,subject,score
 from StuInfo,StuMarks
 where StuInfo.stuid=StuMarks.stuid and stuName=@name
go
exec pr_stu_marks '田七'

IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stu_marks
go 
--有默认参数 没有传递参数时 查询全部,有传递参数时,按条件查询..
create proc pr_stu_marks(@name char(10)=null)
as

 if @name is null
  begin
   select StuInfo.stuid,stuName,subject,score
   from StuInfo,StuMarks
   where StuInfo.stuid=StuMarks.stuid
  end
 else
  begin
   select StuInfo.stuid,stuName,subject,score
   from StuInfo,StuMarks
   where StuInfo.stuid=StuMarks.stuid and stuName=@name
  end
go
exec pr_stu_marks '田七'

--定义输出参数
IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stucount
go 
create proc pr_stucount(@boy int output,@gril int output)--output指定输出
as
 select @boy=COUNT(*) from StuInfo where stusex='男'
 select @gril=COUNT(*) from StuInfo where stusex='女'
go
declare @boy int,@gril int
exec pr_stucount @boy output,@gril output
print '男:'+convert(char(1),@boy)+' 女:'+convert(char(1),@gril)

--抛出异常
go
create proc devide(@a int,@b int,@c int output)
as
 if(@b=0)
  begin
     raiserror ('0不能作为除数',10,2)
     set @c=0
  end
 else
  begin
   set @c=@a/@b
  end
  
declare @c int
exec devide 2,3,@c output --不够整数的小数部分完全截去
print @c

猜你喜欢

转载自blog.csdn.net/TSsansui/article/details/82707132