這是不久前寫的一個(gè)分頁(yè)存儲(chǔ)過程,可應(yīng)用于SQL Server 2005上面:
復(fù)制代碼 代碼如下:
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 /*經(jīng)常會(huì)調(diào)用第1頁(yè),這里做特殊處理,少一層子查詢*/
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
調(diào)用方法:
1.單表:
復(fù)制代碼 代碼如下:
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.多表聯(lián)接:
復(fù)制代碼 代碼如下:
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''
', -- varchar(max)
@Order = '', -- varchar(4000)
@CurrentPage = 3, -- int
@PageSize = 20, -- int
@TotalCount = 0 -- int
注:在@Sql 中不能使用CTE。
您可能感興趣的文章:- 五種SQL Server分頁(yè)存儲(chǔ)過程的方法及性能比較
- SQL Server 分頁(yè)查詢通用存儲(chǔ)過程(只做分頁(yè)查詢用)
- sqlserver2005利用臨時(shí)表和@@RowCount提高分頁(yè)查詢存儲(chǔ)過程性能示例分享
- 深入sql server 2005 萬能分頁(yè)存儲(chǔ)過程的詳解
- 基于Sql Server通用分頁(yè)存儲(chǔ)過程的解決方法
- mssql 高效的分頁(yè)存儲(chǔ)過程分享
- MSSQL MySQL 數(shù)據(jù)庫(kù)分頁(yè)(存儲(chǔ)過程)
- 三種SQL分頁(yè)查詢的存儲(chǔ)過程代碼
- SQL通用存儲(chǔ)過程分頁(yè),支持多表聯(lián)合
- SQL分頁(yè)查詢存儲(chǔ)過程代碼分享