一、简介

简单记录一下存储过程的使用。存储过程是预编译SQL语句集合,也可以包含一些逻辑语句,而且当第一次调用存储过程时,被调用的存储过程会放在缓存中,当再次执行时,则不需要编译可以立马执行,使得其执行速度会非常快。

二、使用

创建格式 create procedure 过程名( 变量名变量类型 ) asbegin ……..end 

create procedure getGroup(@salary int)asbegin SELECT d_id AS '部门编号', AVG(e_salary) AS '部门平均工资' FROM employee  GROUP BY d_id   HAVING AVG(e_salary) > @salaryend

调用时格式,exec过程名 参数

exec getGroup 7000

三、在存储过程中实现分页

3.1 要实现分页,首先要知道实现的原理,其实就是查询一个表中的前几条数据

select top 10 * from table--查询表前10条数据 select top 10 * from table where id not in (select top (10) idfrom tb) --查询前10条数据(条件是id 不属于table 前10的数据中)

3.2 当查询第三页时,肯定不需要前20 条数据,则可以

select top 10 * from table where id not in (select top ((3-1) * 10) idfrom tb) --查询前10条数据(条件是id 不属于table 前10的数据中)

3.3 将可变数字参数化,写成存储过程如下

create proc sp_pager(@size int , --每页大小@index int --当前页码)asbegindeclare @sql nvarchar(1000)if(@index = 1) set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb'else set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb where id not in( select top '+cast((@index-1)*@size as nvarchar(50))+' idfrom tb )'execute(@sql)end

3.4 当前的这种写法,要求id必须连续递增,所以有一定的弊端

所以可以使用row_number(),使用select语句进行查询时,会为每一行进行编号,编号从1开始,使用时必须要使用order by 根据某个字段预排序,还可以使用partition by将 from 子句生成的结果集划入应用了 row_number 函数的分区,类似于分组排序,写成存储过程如下

create proc sp_pager(@size int , --每页大小@index int --当前页码)asbegindeclare @sql nvarchar(1000)if(@index = 1) set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb'else set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb where id not in( select top '+cast((@index-1)*@size as nvarchar(50))+' idfrom tb )'execute(@sql)end

好了, 以上是本文所有内容,希望对大家有所帮助,也希望大家对码农之家多多支持,你们的支持是我创作的动力!祝大家生活愉快!