利用表变量分页
在上面的代码中,如果EmployeeID是唯一的(一般在数据库设计的时候推荐在表中加一个自增列的字段来取代它),可以不用表变量切性能可进一步得到优化,具体代码如下:
优化的分页程序
在SQL Server 2005和Oracle 9i后的版本中可以分别使用ROWNUMBER和ROWNUM来进行分页,并能获得较好的性能,以SQL Server 2005为例,一般的做法如下:
1SELECT
2FROM
3 (SELECT
4 ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
5 FROM Employees e
6 ) as DerivedTableName
7WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
8
9
但是有一个小问题,如果最里面的一层查询有重复值,上面的排序将会出现问题,最好将代码优化成如下形式:2FROM
3 (SELECT
4 ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
5 FROM Employees e
6 ) as DerivedTableName
7WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
8
9
1SELECT
2(
3 SELECT ,
4 ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
5 FROM
6 (SELECT DISTINCT
7 FROM Employees e
8 INNER JOIN f
9 ON e.id = f.id
10 ) AS DerivedTableName
11) AS Temp
12WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
之所以要这么做是为了是DISTINCT发挥作用,因为在SQL Server2005中DISTINCT和ROW_NUMBER()一起使用,DISTINCT将不能过滤掉重复的记录,在Oracle中DISTINCT和ROWNUM也会同样出现这样的问题,这些都是本人在实际项目中遇到的问题并总结出来的,或许你有更好的方法,可以在我的博客中留言,谢谢!2(
3 SELECT ,
4 ROW_NUMBER() OVER(ORDER BY ColumnName) as RowNum
5 FROM
6 (SELECT DISTINCT
7 FROM Employees e
8 INNER JOIN f
9 ON e.id = f.id
10 ) AS DerivedTableName
11) AS Temp
12WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
参考文章:http://aspnet.4guysfromrolla.com/articles/031506-1.aspx