您的位置:首页 > 其它

存储过程

2016-03-13 20:24 295 查看
一.存储过程定义:

接收在数据库服务器上存储的预先编译好的一堆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关键字

六.带参数的存储过程

例:

alter procedure usp_GetStuResult
@PassScore int=90,
@name nvarchar(20)
--as之前给参数
as
if(@PassScore>=0 and @PassScore<=100)
begin
select studentname,studentresult
from student,result
where student.studentno=result.studentno
and
studentresult>@PassScore
end
else
begin
raiserror('及格线输入有误',16,1)
end

--开始测试存储过程书写是否存在问题
exec usp_GetStuResult @name='张三'


raiserror用法:

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

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

alter proc usp_getpaglist
@pageindex, int--当前是第几页
@pagesize,--每页的记录数
@totalpages int output--总页数
as
select * from
(
select * ,row_number()over(order by studentno)as myid
from student
)as tmp
where myid between(@pageindex-1)*@pagesize+1 and@ pageindex * @pagesize
--总记录数=总记录数/@pagesize
declare @totalrecord int
select  @totalrecord   =count(1) from student
set @totalpages =ceiling( @totalrecord  *1.0/@pagesize)
--调用
declare @pages int
set @pages=0
exec usp_getpagelist 1,3@pages output
print @pages
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: