1
ALTER PROCEDURE pagination
2
@tblName varchar(255), -- 表名
3
@strGetFields varchar(1000) = '*', -- 需要返回的列
4
@fldName varchar(255)='', -- 排序的字段名
5
@PageSize int , -- 页尺寸
6
@PageIndex int, -- 页码
7
@doCount bit , -- 返回记录总数, 非 0 值则返回
8
@OrderType bit , -- 设置排序类型, 非 0 值则降序
9
@strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
10
AS
11
declare @strSQL varchar(5000) -- 主语句
12
declare @strTmp varchar(110) -- 临时变量
13
declare @strOrder varchar(400) -- 排序类型
14
15
if @doCount != 0
16
begin
17
if @strWhere !=''
18
set @strSQL = "select count(*) as Total from [" + @tblName + "] where "+@strWhere
19
else
20
set @strSQL = "select count(*) as Total from [" + @tblName + "]"
21
end
22
--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都是@doCount为0的情况
23
else
24
begin
25
26
if @OrderType != 0
27
begin
28
set @strTmp = "<(select min"
29
set @strOrder = " order by [" + @fldName +"] desc"
30
--如果@OrderType不是0,就执行降序,这句很重要!
31
end
32
else
33
begin
34
set @strTmp = ">(select max"
35
set @strOrder = " order by [" + @fldName +"] asc"
36
end
37
38
if @PageIndex = 1
39
begin
40
if @strWhere != ''
41
set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from [" + @tblName + "] where " + @strWhere + " " + @strOrder
42
else
43
set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["+ @tblName + "] "+ @strOrder
44
--如果是第一页就执行以上代码,这样会加快执行速度
45
end
46
else
47
begin
48
--以下代码赋予了@strSQL以真正执行的SQL代码
49
set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["
50
+ @tblName + "] where [" + @fldName + "]" + @strTmp + "(["+ @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["+ @fldName + "] from [" + @tblName + "]" + @strOrder + ") as tblTmp)"+ @strOrder
51
52
if @strWhere != ''
53
set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["
54
+ @tblName + "] where [" + @fldName + "]" + @strTmp + "(["
55
+ @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["
56
+ @fldName + "] from [" + @tblName + "] where " + @strWhere + " "
57
+ @strOrder + ") as tblTmp) and " + @strWhere + " " + @strOrder
58
end
59
end
60
exec (@strSQL)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
网页调用:
1
private static DataSet GetCustomersData(string tblName, string strGetFields, string fldName, int PageSize, int PageIndex, int doCount, int OrderType, string strWhere)
2
}
具体调用:2
1、返回记录数
2、返回记录集