--分页储存过程
if exists (select * from sys.procedures where name='Page')
drop proc Page
go
create proc Page
@PageIndex int=2, --页码
@PageSize int=10,--记录数
@PageSum int output--总数
as
--得到总页数
select @PageSum=CEILING(COUNT(*)*1.0/@PageSize) from Teacher
--查询分页
Select * from (select ROW_NUMBER() over(Order by teacherID) 排序 ,* from Teacher) s --新建一列作为所有数据的连续顺序排列
--(注解:‘s’ 为别名,不可缺少。'排序' 为新建列)
where 排序>(@PageIndex-1)*@PageSize--约束起始位置
and 排序<=@PageIndex*@PageSize--约束终止位置
--ROM_NUMBER()语法
语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
简单的说row_number()从1开始,为每一条分组记录返回一个数字,这里的ROW_NUMBER() OVER (ORDER BY xlh DESC) 是先把xlh列降序,再为降序以后的没条xlh记录返回一个序号。
示例:
xlh row_num
1700 1
1500 2
1085 3
710 4 row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)
实例:
初始化数据
create table employee (empid int ,deptid int ,salary decimal(10,2))
insert into employee values(1,10,5500.00)
insert into employee values(2,10,4500.00)
insert into employee values(3,20,1900.00)
insert into employee values(4,20,4800.00)
insert into employee values(5,40,6500.00)
insert into employee values(6,40,14500.00)
insert into employee values(7,40,44500.00)
insert into employee values(8,50,6500.00)
insert into employee values(9,50,7500.00) 数据显示为
empid deptid salary
----------- ----------- ---------------------------------------
1 10 5500.00
2 10 4500.00
3 20 1900.00
4 20 4800.00
5 40 6500.00
6 40 14500.00
7 40 44500.00
8 50 6500.00
9 50 7500.00