SQL Server 2005通用分页存储过程及多表联接应用
前端之家收集整理的这篇文章主要介绍了
SQL Server 2005通用分页存储过程及多表联接应用,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是不久前写的一个分页存储过程,可应用于sql Server 2005上面:
<div class="codetitle"><a style="CURSOR: pointer" data="95197" class="copybut" id="copybut95197" onclick="doCopy('code95197')"> 代码如下:
<div class="codebody" id="code95197">
if object_ID('[proc_SelectForPager]') is not null
Drop Procedure [proc_SelectForPager]
Go
Create Proc proc_SelectForPager
(
@
sql varchar(max),
@Order varchar(4000),
@CurrentPage int,
@PageSize int,
@TotalCount int output
)
As
/
Andy 2012-2-28 /
Declare @Exec_
sql nvarchar(max)
Set @Exec_
sql='Set @TotalCount=(Select Count(1) From ('+@
sql+') As a)'
Exec sp_execute
sql @Exec_
sql,N'@TotalCount int output',@TotalCount output
Set @Order=isnull(' Order by '+nullif(@Order,''),' Order By getdate()')
if @CurrentPage=1 /
经常会调用第1页,这里做特殊处理,少一层子查询/
Set @Exec_
sql='
;With CTE_Exec As
(
'+@
sql+'
)
Select Top(@pagesize)
,row_number() Over('+@Order+') As r From CTEExec Order By r
'
Else
Set @Execsql='
;With CTE_Exec As
(
Select ,row_number() Over('+@Order+') As r From ('+@
sql+') As a
)
Select
From CTE_Exec Where r Between (@CurrentPage-1)@pagesize+1 And @CurrentPage
@pagesize Order By r
'
Exec sp_executesql @Exec_sql,N'@CurrentPage int,@PageSize int',@CurrentPage,@PageSize
Go