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_executesql @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 CTE_Exec Order By r

Else
Set @Exec_sql=’
;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

调用方法


1.单表


<div class=”codetitle”><a style=”CURSOR: pointer” data=”86911″ class=”copybut” id=”copybut86911″ onclick=”doCopy(‘code86911’)”> 代码如下:<div class=”codebody” id=”code86911″>
Exec proc_SelectForPager @Sql = ‘Select
from contacts a where a.ContactType=1′,– varchar(max)
@Order = ”,– varchar(4000)
@CurrentPage = 3,– int
@PageSize = 20,– int
@TotalCount = 0 — int

2.多表联接


<div class=”codetitle”><a style=”CURSOR: pointer” data=”64885″ class=”copybut” id=”copybut64885″ onclick=”doCopy(‘code64885’)”> 代码如下:<div class=”codebody” id=”code64885″>
Exec proc_SelectForPager @Sql =
‘Select a.Staff,a.OU,b.FName+b.FName as Name
from staffOUHIST a
inner join Staff b on b.ID=a.Staff and a.ExpiryDate=”30001231”
‘,– int
@TotalCount = 0 — int

:在@Sql 中不能使用CTE。

作者: dawei

【声明】:永州站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部