SqlServer 分页学习
在B站上看到一个分页视频,老师讲的挺好 ,记录下来。想看原视频的可以去B站
--1.建立Students表
CREATE TABLE students (
ID INT PRIMARY KEY IDENTITY(1,2),
NAME NVARCHAR(50) NOT NULL,
SEX CHAR(6) CHECK (SEX IN ('Male', 'Female'))
);
GO
--2. 插入30条数据
INSERT INTO students (NAME, SEX)
VALUES
('关羽', 'Male'),
('张飞', 'Male'),
('赵云', 'Male'),
('马超', 'Male'),
('黄忠', 'Male'),
('诸葛亮', 'Male'),
('曹操', 'Male'),
('刘备', 'Male'),
('孙权', 'Male'),
('周瑜', 'Male'),
('司马懿', 'Male'),
('夏侯惇', 'Male'),
('许褚', 'Male'),
('典韦', 'Male'),
('庞统', 'Male'),
('姜维', 'Male'),
('陆逊', 'Male'),
('魏延', 'Male'),
('张辽', 'Male'),
('徐晃', 'Male'),
('甘宁', 'Male'),
('太史慈', 'Male'),
('吕蒙', 'Male'),
('孙尚香', 'Female'), -- 作为例子,孙尚香是女性
('祝融夫人', 'Female'), -- 祝融夫人是孟获之妻,在《三国演义》中有出场
('马云騄', 'Female'), -- 马超之妹,在民间传说中出现
('邹氏', 'Female'), -- 张济之妻,在《三国演义》中提到
('蔡文姬', 'Female'), -- 著名才女
('貂蝉', 'Female'); -- 在《三国演义》中著名的虚构人物
--3.分页:假设每页5条数据
--查询第一页
select top 5 * from students
--第二页
select top 5 * from students where id not in(1,3,5,7,9)
--select top 5 * from students where id not in(1,3,5,7,9)
1,3,5,7,9有点麻烦,可以替换一下
使用select top 5 id from students
select top 5 * from students
where
id not in(select top 5 id from students)
-- 第三页
select top 5 * from students
where
id not in(select top 10 id from students)
--推公式
select top 每页数量 * from students
where
id not in(select top 每页数量*(当前页-1) id from students)
--定义变量:top后如果是变量需要把变量用括号包裹
declare @PageSize int=5
declare @PageIndex int =1
select top (@PageSize) * from students
where id not in(select top (@PageSize*(@PageIndex-1)) id from students)