存储过程

一.存储过程定义:

接收在数据库服务器上存储的预先编译好的一堆SQL语句

二.存储过程的优点:

1.执行速度快(预编译:可以看成编译后的中间代码,存储过程将会在SQL SERVER服务器上进行预编译

2.允许模式化程序设计

3.安全性更高

4.减少网络流量

三.存储过程的分类:

1.系统存储过程:一般以sp开头(stored Procedure),由sql server 创建.管理和使用,存放在resource数据库中,类似于C#中的方法.

2.扩展存储过程:一般以xp开头,使用编辑语言(如C#)创建的外部存储过程,以DELL的形式单独存在.

3.用户自定义存储过程:一般以usp开头,由用户在自己的数据库中创建的存储过程(类似于C#中自定义的方法).

四.常用的系统存储过程:

sp_databases 列出服务器上的所有数据库

exec sp_databases 

sp_helpdb 报告有关指定数据库或所有数据库的信息

sp_renamedb 更改数据库的名称

sp_tables 返回当前环境下可查询的对象的列表

sp_columns 返回某个表列的信息

sp_help 查看某个表的所有信息

sp_helpconstraint 查看某个表的约束

sp_helpindex 查看某个表的索引

sp_stored_procedures 列出当前环境中的所有存储过程

sp_password 添加或修改登录帐户的密码

sp_helptext 显示默认值、未加密的存储过程、用户定义的存储过程、触发器或视图的实际文本

五.用户自定义的存储过程

语法:

Create Procedure usp_info

as

select

注意:1.参数置于as前,且不用declare关键字

      2.as后的变量需要declare关键字

六.带参数的存储过程

例:

 1 alter procedure usp_GetStuResult
 2    @PassScore int=90,
 3    @name nvarchar(20)
 4    --as之前给参数
 5 as
 6 if(@PassScore>=0 and @PassScore<=100)
 7 begin
 8 select studentname,studentresult
 9 from student,result
10 where student.studentno=result.studentno
11 and 
12 studentresult>@PassScore
13 end
14 else
15 begin
16   raiserror('及格线输入有误',16,1)
17 end 
18 
19 --开始测试存储过程书写是否存在问题
20 exec usp_GetStuResult @name='张三'

raiserror用法:

raiserror返回用户定义的错误信息时,可指定严重级别.设置系统变量记录所发生的错误

七.带output参数的存储过程:

 1 alter proc usp_getpaglist
 2 @pageindex, int--当前是第几页
 3 @pagesize,--每页的记录数
 4 @totalpages int output--总页数
 5 as
 6 select * from 
 7       (
 8         select * ,row_number()over(order by studentno)as myid
 9         from student
10        )as tmp
11 where myid between(@pageindex-1)*@pagesize+1 and@ pageindex * @pagesize
12 --总记录数=总记录数/@pagesize
13 declare @totalrecord int
14 select  @totalrecord   =count(1) from student
15 set @totalpages =ceiling( @totalrecord  *1.0/@pagesize)
16 --调用
17 declare @pages int
18 set @pages=0
19 exec usp_getpagelist 1,3@pages output
20 print @pages

     

原文地址:https://www.cnblogs.com/chimingyang/p/5273002.html