初入Sql Server 之 存储过程的简单使用

一、简介

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

二、使用

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

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

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

exec getGroup 7000

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

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

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

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

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

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

create proc sp_pager
(
 @size int , --每页大小
 @index int --当前页码
)
as
begin
 declare @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))+' id from 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
)
as
begin
 select * from ( select row_number() over(order by id ) as [rowId], * from table) as b
 where [rowId] between @size*(@index-1)+1 and @size*@index
end

 

作者:just--like原文地址:https://www.cnblogs.com/just-like/p/16659395.html

%s 个评论

要回复文章请先登录注册