剛開始學習分頁儲存過程的時候看到有很多長篇大論的**,看起來很亂,現在有乙個很好的分頁儲存過程,分享一下:
alter procedure [dbo].[pr_page_helper]
@top int=null, --- 返回前n位記錄 -1 :全部
@ascordesc bit =null, ---1 :desc 0:asc
@column nvarchar(2024) = null, ---返回的字段
@sqlwhere nvarchar(1024) = null, ---過濾條件
@orderby nvarchar(1024) = null, --排序關鍵字 --還真不能空
@tablename nvarchar(100)=null, -- 表名
@currentpage int = null, --頁碼
@pagesize int = null, --一頁的記錄條數
@totalcount int = null output --記錄總數
--@currentpage 和 @pagesize 同時不為空時則分頁,其他則是返回前n個記錄
asbegin
declare @sql nvarchar(max)
declare @tmp_sql nvarchar(max)
if isnull(@currentpage,0)>0 and isnull(@pagesize,0)>0
begin
declare @n_begin int
declare @n_end int
set @n_begin = @pagesize*(@currentpage-1)+1
set @n_end = @pagesize*@currentpage
set @tmp_sql = n'select @pc1 = count(*) '+n' from '+@tablename
if not @sqlwhere is null set @tmp_sql = @tmp_sql + n' where ' + @sqlwhere
execute sp_executesql @tmp_sql, n'@pc1 int output', @pc1= @totalcount output
set @sql = n' select '+ @column +n', row_number() over(order by ' + @orderby
if isnull(@ascordesc, 0) > 0
set @sql = @sql + n' desc ) as row_number '
else
set @sql = @sql + n' asc ) as row_number '
set @sql = @sql + n' from '+@tablename
if not @sqlwhere is null set @sql = @sql + n' where ' + @sqlwhere
set @sql = n'with t as(' + @sql + n') select * from t where t.row_number between @between and @end'
execute sp_executesql @sql, n'@between int, @end int', @between = @n_begin, @end = @n_end
print @sql
print @tmp_sql
select @totalcount
endelse
begin
set @sql = n'select '
if isnull(@top, 0) > 0 set @sql = @sql + n' top ' + cast(@top as nvarchar) + n' '
set @sql = @sql+ @column + n' from '+@tablename
if not @sqlwhere is null set @sql = @sql + n' where ' + @sqlwhere
if not @orderby is null
begin
set @sql = @sql + n' order by ' + @orderby
if isnull(@ascordesc, 0) > 0
set @sql = @sql + n' desc '
else
set @sql = @sql + n' asc '
endprint @sql
execute sp_executesql @sql
endend
SqlServer2005分頁方案
插入測試資料200w條,可能會很久 create table student id int primary keyidentity 1 1 name nvarchar 50 age int insert student name,age values name 18 while select cou...
SQL Server 2005 分頁儲存過程
支援 多表連線查詢 group by分組查詢等。多表連線查詢時請指定字段,不要用select 返回為一結果集,有乙個輸出引數為記錄總數,配合 aspnetpager控制項使用絕配。create procedure web pager rowstotal intoutput,輸出記錄總數 tablen...
sqlserver2005 分頁 SQL語句
1.分頁方案一 利用not in和select top分頁 語句形式 select top 10 from testtable where id not in select top20id from testtable order by id order by id select top 頁大小 f...