存储过程基本知识

来源:互联网 发布:水准仪测量数据图片 编辑:程序博客网 时间:2024/06/05 19:07
存储过程是在大型数据库系统中,一组为了完成特定功能的SQL语句集,
存储在数据库中,经过一次调用不需要再次编译,用户通过指定存储过程的
名字并给出参数(如果该存储过程带有参数)来执行它。存储过成是数据库
中的一个重要对象。


基本语法:
1、创建存储过程
create procedure sp_name
@[参数名] [类型],@[参数名] [类型]
as
begin
.........
end
以上格式还可以简写成:
create proc sp_name
@[参数名] [类型],@[参数名] [类型]
as
begin
.........
end
/*注:“sp_name”为需要创建的存储过程的名字,该名字不可以以阿拉伯数字开头*/


2、调用存储过程:
exec sp_name [参数名]


3、删除存储过程
drop procedure sp_name
不能在一个存储过程中删除另一个存储过程,只能调用另一个存储过程


4、其他
show procedure status
显示数据库中所有存储的存储过程基本信息,包括所属数据库,存储过程名称,创建时间等


show create procedure sp_name
显示某一个mysql存储过程的详细信息


exec sp_helptext sp_name
显示你这个sp_name这个对象创建文本




三个典型的SQL存储过程的例子


create proc proc_stu 
@sname varchar(20), 
@pwd varchar(20) 
as 
select * from ren where sname=@sname and pwd=@pwd 
go


查看结果:proc_stu 'admin','admin'


例2:


下面的存储过程实现用户验证的功能,如果不成功,返回0,成功则返回1.


CREATE PROCEDURE VALIDATE @USERNAME CHAR(20),@PASSWORD CHAR(20),@LEGAL BIT OUTPUT 
AS


IF EXISTS(SELECT * FROM REN WHERE SNAME = @USERNAME AND PWD = @PASSWORD) 
SELECT @LEGAL = 1 
ELSE 
SELECT @LEGAL = 0


在程序中调用该存储过程,并根据@LEGAL参数的值判断用户是否合法。


例3:一个高效的数据分页的存储过程 可以轻松应付百万数据


CREATE PROCEDURE pageTest --用于翻页的测试
--需要把排序字段放在第一列


(
@FirstID nvarchar(20)=null, --当前页面里的第一条记录的排序字段的值
@LastID nvarchar(20)=null, --当前页面里的最后一条记录的排序字段的值
@isNext bit=null, --true 1 :下一页;false 0:上一页
@allCount int output, --返回总记录数
@pageSize int output, --返回一页的记录数
@CurPage int --页号(第几页)0:第一页;-1最后一页。
)


AS


if @CurPage=0--表示第一页
begin
--统计总记录数
select @allCount=count(ProductId) from Product_test 


set @pageSize=10
--返回第一页的数据
select top 10 
ProductId,
ProductName,
Introduction 
from Product_test order by ProductId 
end


else if @CurPage=-1--表示最后一页


select * from 
(select top 10 ProductId,
ProductName,
Introduction


from Product_test order by ProductId desc ) as aa 
order by ProductId
else


begin 
if @isNext=1
--翻到下一页
select top 10 ProductId,
ProductName,
Introduction
from Product_test where ProductId > @LastID order by ProductId 
else
--翻到上一页
select * from
(select top 10 ProductId,
ProductName,
Introduction
from Product_test where ProductId < @FirstID order by ProductId desc) as bb order by ProductId
end
原创粉丝点击