存储过程分页

 1 ALTER proc [dbo].[CreatePage]
 2  @thisPage int,--当前页数
 3  @pageSize int,--每页多少条记录
 4  @tableName varchar(100)='',--表名
 5  @columns varchar(4000) = '*',--查询列名
 6  @pkColumn varchar(50) = '' ,--主键
 7  @condition varchar(2000)='',--条件需要加and 不需要where
 8  @ascColumn varchar(100) = '', --排序的字段名 (即 order by column asc/desc)
 9  @OrderType varchar(10)='asc',  --排序的类型 
10  @totalPageNum int output
11  as
12  begin
13      declare @sqlTotalCount nvarchar(2000)--获得总条数sqlstr
14      
15      declare @sqlStr nvarchar(4000)--获得表的sqlstr
16      declare @totalCount int --总条数
17      declare @totalPage int --总页数    
18      declare @startRowNum int --每页开始的行号
19      declare @endRowNum int --每页结束的行号
20      
21      if @ascColumn=''
22      begin
23          set @ascColumn=@pkColumn--如果没有则 按主键排序
24      end
25  
26  
27      set @sqlTotalCount= 'select @count=COUNT(*) from ' + @tableName
28      exec sp_executesql @sqlTotalCount, N'@count int output' , @totalCount output
29      
30      --select @totalCount --总记录数
31      
32      set @totalPage=@totalCount/@pageSize --设置总页数
33     if (@totalCount % @pageSize <> 0)
34          begin
35             set @totalPage=@totalPage+1
36          end
37 
38 
39      set    @startRowNum=(@thisPage-1)*@pageSize+1 --设置每页开始的行号
40      set @endRowNum=@thisPage*@pageSize  --设置每页结束的行号
41      
42     
43     if @thisPage=1
44     begin
45         set @sqlStr= 'select top' + str(@pageSize) + ' ' + @columns + 
46                     ' from ' + @tableName + ' where 1=1 ' +  @condition +
47                     'order by ' + @ascColumn + ' ' + @OrderType 
48                         

49     end
50     else
51     begin
52     set @sqlStr = 'select * from  
53                      (
54                        select top 100 percent ' +  @columns  +  ',
55                          ROW_NUMBER() over (order by '+ @ascColumn + ' '+ @OrderType +') 
56                           Rowindex from '+ @tableName + ' where 1=1 '+  @condition +
57                      
58                    ' ) T1 
59                          where '+
60                           'Rowindex>='+STR(@startRowNum) + ' 
61                         and Rowindex<='+STR(@endRowNum)
62                          
63     end
64      print @sqlStr
65     
66 
67     set @totalPageNum=@totalPage --总页数
68     
69      exec (@sqlStr)
70          
71  end
72 
73 
74 
75 
76 declare @p9 int
77 set @p9=1
78 exec CreatePage @thisPage=1,
79         @pageSize=10,@tableName=N'PE_MultiLevelComment',
80         @columns=N'Id',@pkColumn=N'Id',@condition=N'',
81         @ascColumn=N'',@OrderType=N'',@totalPageNum =@p9 output
82 select @p9
原文地址:https://www.cnblogs.com/yangjingqi/p/3134435.html