1
CREATE PROCEDURE P_newpager
2
3
@tblname VARCHAR(255), -- 表名
4
5
@strGetFields nvarchar(1000) = "*", -- 需要返回的列
6
7
@fldName varchar(255)='', -- 排序的字段名
8
9
@PageSize int = 10, -- 页尺寸
10
11
@PageIndex int = 1, -- 页码
12
13
@doCount bit = 0, -- 返回, 非0 值则返回记录总数
14
15
@OrderType bit = 0, -- 设置排序类型, 非0 值则降序
16
17
@strWhere varchar(1500) = '' -- 查询条件(注意: 不要加where)
18
19
AS
20
21
declare @strSQL varchar(5000) -- 主语句
22
23
declare @strTmp varchar(110) -- 临时变量
24
25
declare @strOrder varchar(400) -- 排序类型
26
27
if @doCount != 0
28
29
begin
30
31
if @strWhere !=''
32
33
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 '+ @strWhere
34
35
else
36
37
set @strSQL = 'select count(*) as Total from [' + @tblName + ']'
38
39
end --以上代码的意思是如果@doCount传递过来的不是,就执行总数统计。以下的所有代码都是@doCount为的情况:
40
41
else
42
43
begin
44
45
if @OrderType != 0--降序
46
47
begin
48
49
set @strTmp = '<(select min'
50
51
set @strOrder = ' order by [' + @fldName +'] desc'--如果@OrderType不是0,就执行降序,这句很重要!
52
53
end
54
55
else
56
57
begin
58
59
set @strTmp = '>(select max'
60
61
set @strOrder = ' order by [' + @fldName +'] asc'
62
63
end
64
65
if @PageIndex = 1
66
67
begin
68
69
if @strWhere != ''
70
71
set @strSQL = 'select top ' + str(@PageSize) +' ' + @strGetFields + ' from [' + @tblName + '] where 1=1 ' + @strWhere + ' ' + @strOrder
72
73
else
74
75
set @strSQL = 'select top ' + str(@PageSize) +' ' + @strGetFields + ' from [' + @tblName + '] ' + @strOrder--如果是第一页就执行以上代码,这样会加快执行速度
76
77
end
78
79
else
80
81
begin--以下代码赋予了@strSQL以真正执行的SQL代码
82
83
set @strSQL = 'select top ' + str(@PageSize) + ' ' + @strGetFields + ' from [' + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' [' + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)' + @strOrder
84
85
if @strWhere != ''
86
87
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from [' + @tblName + '] where [' + @fldName + ']' + @strTmp + '([' + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' [' + @fldName + '] from [' + @tblName + '] where 1=1 ' + @strWhere + ' ' + @strOrder + ') as tblTmp) and 1=1 ' + @strWhere + ' ' + @strOrder
88
89
end
90
91
if @strWhere !='' --得到记录的总行数
92
93
set @strSQL =@strSQL+ '; select count(*) as Total from [' + @tblName + '] where 1=1 '+ @strWhere
94
95
else
96
97
set @strSQL =@strSQL+ '; select count(*) as Total from [' + @tblName + ']'
98
99
end
100
101
exec (@strSQL)
102
103
RETURN
104
105
106
GO
107

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

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107
