建立表:
1 CREATE TABLE [TestTable] ( 2 [ID] [int] IDENTITY (1, 1) NOT NULL , 3 [FirstName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL , 4 [LastName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL , 5 [Country] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL , 6 [Note] [nvarchar] (2000) COLLATE Chinese_PRC_CI_AS NULL 7 ) ON [PRIMARY] 8 GO 9 10 插入数据:(2万条,用更多的数据测试会明显一些) 11 SET IDENTITY_INSERT TestTable ON 12 declare @i int 13 set @i=1 14 while @i<=20000 15 begin 16 insert into TestTable([id], FirstName, LastName, Country,Note) values(@i, 'FirstName_XXX','LastName_XXX','Country_XXX','Note_XXX') 17 set @i=@i+1 18 end 19 SET IDENTITY_INSERT TestTable OFF
分页方案一:(利用Not In和SELECT TOP分页)
1 SELECT TOP 10 * 2 FROM TestTable 3 WHERE (ID NOT IN 4 (SELECT TOP 20 id 5 FROM TestTable 6 ORDER BY id)) 7 ORDER BY ID 8 9 SELECT TOP 页大小 * 10 FROM TestTable 11 WHERE (ID NOT IN 12 (SELECT TOP 页大小*页数 id 13 FROM 表 14 ORDER BY id)) 15 ORDER BY ID
分页方案二:(利用ID大于多少和SELECT TOP分页)
1 SELECT TOP 10 * 2 FROM TestTable 3 WHERE (ID > 4 (SELECT MAX(id) 5 FROM (SELECT TOP 20 id 6 FROM TestTable 7 ORDER BY id) AS T)) 8 ORDER BY ID 9 10 SELECT TOP 页大小 * 11 FROM TestTable 12 WHERE (ID > 13 (SELECT MAX(id) 14 FROM (SELECT TOP 页大小*页数 id 15 FROM 表 16 ORDER BY id) AS T)) 17 ORDER BY ID
分页方案三:(利用SQL的游标存储过程分页)
1 create procedure XiaoZhengGe 2 @sqlstr nvarchar(4000), --查询字符串 3 @currentpage int, --第N页 4 @pagesize int --每页行数 5 as 6 set nocount on 7 declare @P1 int, --P1是游标的id 8 @rowcount int 9 exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output 10 select ceiling(1.0*@rowcount/@pagesize) as 总页数--,@rowcount as 总行数,@currentpage as 当前页 11 set @currentpage=(@currentpage-1)*@pagesize+1 12 exec sp_cursorfetch @P1,16,@currentpage,@pagesize 13 exec sp_cursorclose @P1 14 set nocount off
其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。
总结:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用
在实际情况中,要具体分析。