现在的位置: 首页 > 综合 > 正文

sql单表简单的分页脚本

2012年08月16日 ⁄ 综合 ⁄ 共 999字 ⁄ 字号 评论关闭
/*m:代表总记录数(m>0)
n:代表每页显示N条记录(n>0)
page:代表当前页(page从0开始)
求总页数:(m%n)==0?(m/n):(m/n+1);
SQL语句的实现:
*/

--创建test表进行测试
if object_id('test'is null--判断表是否存在
create table test
(
  id 
int identity(1,1primary key,
  title 
nvarchar(255) ,
  con 
nvarchar(255)
)

--循环插入多条数据
declare @title nvarchar(255)
declare @con nvarchar(255)
declare @start int
declare @all int
set @start=0
set @all=10000
while @start<@all
begin 
  
insert into test values('testtitle','testcon')
  
set @start=@start+1;
  
end
  
--插入数据结束

--单表分页存储过程
--判断存储过程是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[partPage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
-- 删除存储过程
drop procedure [dbo].[partPage]
GO
create proc partPage
@n int,--每页数量
@page int --页码从0开始
as
declare @sql nvarchar(1000)
begin
set @sql='select top '+cast(@n as varchar(50))+' * from test where id not in(select top ('+cast((@n *@page) as varchar(50))+') id from test order by id) order by id'
exec(@sql)
end
--存储过程结束

--测试
--每页显示10条,取出第15页的数据
exec partPage 10,14

select top 10 * from test where id not in(select top (10*14) id from test order by id) order by id

 

 

抱歉!评论已关闭.