来源:http://dev.csdn.net/article/37/37213.shtm
![](/Images/OutliningIndicators/ContractedBlock.gif)
建立表
1
建立表:
2![](/Images/OutliningIndicators/None.gif)
3
CREATE TABLE [TestTable] (
4
[ID] [int] IDENTITY (1, 1) NOT NULL ,
5
[FirstName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
6
[LastName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
7
[Country] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
8
[Note] [nvarchar] (2000) COLLATE Chinese_PRC_CI_AS NULL
9
) ON [PRIMARY]
10
GO
11![](/Images/OutliningIndicators/None.gif)
12![](/Images/OutliningIndicators/None.gif)
分页方案一:(利用Not In和SELECT TOP分页)
语句形式:
![](/Images/OutliningIndicators/ContractedBlock.gif)
方案一
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![](/Images/OutliningIndicators/None.gif)
9![](/Images/OutliningIndicators/None.gif)
10
SELECT TOP 页大小 *
11
FROM TestTable
12
WHERE (ID NOT IN
13
(SELECT TOP 页大小*页数 id
14
FROM 表
15
ORDER BY id))
16
ORDER BY ID
17![](/Images/OutliningIndicators/None.gif)
分页方案二:(利用ID大于多少和SELECT TOP分页)
语句形式:
![](/Images/OutliningIndicators/ContractedBlock.gif)
方案二
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![](/Images/OutliningIndicators/None.gif)
10![](/Images/OutliningIndicators/None.gif)
11
SELECT TOP 页大小 *
12
FROM TestTable
13
WHERE (ID >
14
(SELECT MAX(id)
15
FROM (SELECT TOP 页大小*页数 id
16
FROM 表
17
ORDER BY id) AS T))
18
ORDER BY ID
19![](/Images/OutliningIndicators/None.gif)
分页方案三:(利用SQL的游标存储过程分页)
![](/Images/OutliningIndicators/ContractedBlock.gif)
方案三
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
其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。
通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用
更多的讨论见:
http://community.csdn.net/Expert/topic/3292/3292678.xml?temp=.1621515