1create
procedure
[dbo
].[pro_getpagedata]2
3(45
@tablename
nvarchar(3000), --表名6
7@returnfields
nvarchar(3000) ='*
', --
需要返回的列 89
@pagesize
int=
10, --
每頁記錄數
1011
@pageindex
int=
0, --
當前頁碼
1213
@where
nvarchar(3000) =
'', --
查詢條件
1415
@orderby
nvarchar(200), --
排序欄位名 最好為唯一主鍵
1617
@ordertype
int=1--
排序型別 1:降序 其它為公升序
1819)20
21as
2223
declare
@totalrecord
int24
25declare
@totalpage
int26
27declare
@currentpagesize
int28
29declare
@totalrecordforpageindex
int30
31declare
@countsql
nvarchar(4000
) 32
3334
35if
@ordertype=1
3637
begin
3839
set@orderby='
order by '+
replace(@orderby,'
,','
desc,
') +
'desc '40
41end
4243
else
4445
begin
4647
set@orderby='
order by '+
replace(@orderby,'
,','
asc,
') +
'asc '48
49end
5051
5253
--總記錄
5455
set@countsql='
select @totalrecord=count(*) from '+
@tablename+'
'+@where
5657
execute sp_executesql @countsql,n'
@totalrecord int out
',@totalrecord
out58
5960
61set
@totalpage
=(@totalrecord
-1)/
@pagesize+1
6263
6465
--查詢頁數不得大於總頁數
6667
if(@pageindex
>
@totalpage)68
69set
@pageindex
=@totalpage
7071
7273
set@currentpagesize
=(@pageindex
-1)*
@pagesize
7475
7677
7879
--返回記錄
8081
set@totalrecordforpageindex
=@pageindex
*@pagesize
8283
8485
exec ('
select *
8687
from (select top '+
@totalrecordforpageindex+'
'+@returnfields+'
, row_number() over ('+
@orderby+'
) as rownum
8889
from '+
@tablename+'
'+@where+'
) as temptable
9091
where temptable.rownum >
9293'+
@currentpagesize)94
9596
9798
99--
返回總頁數和總記錄
100101
select
@totalpage
as pagecount,@totalrecord
as recordcount
SQL SERVER分頁儲存過程
使用儲存過程寫乙個分頁查詢 select from t users gocreate proc usp getdatafy pagesize int 10,每頁記錄條數 定義變數並賦初始值 pageindex int 1,當前要檢視第幾頁的記錄 sumcount int output,總的記錄條數 ...
SqlServer分頁儲存過程
高效分頁語句 1 row number select from select row number over order byrpid as rowfrom ou rolepermission as twheret.row 0 andt.row 10 2,top 分頁查詢 select top 10...
sql server 分頁儲存過程
sql server 分頁儲存過程,在網上找了很多,但是都不能用或者不能很好的用,特別綜合大家的智慧型,自己寫了乙個,而且通過visual studio除錯,通過實際資料測試 set ansi nulls on set quoted identifier on go alter procedure ...