首页 > 代码库 > 【原创】SQL分页查询存储过程

【原创】SQL分页查询存储过程

 1 -------------------------------------
 2 -----作者:张欣宇
 3 -----时间:2013-06-28
 4 -----简介:根据参数和条件分页查询
 5 -------------------------------------
 6 Create proc [dbo].[Up_PagingQueryByParameter]
 7 (
 8     ----- 表名或能查询到结果的SQL语句{SQL语句左右必须有括号例:(select * from tbl1)}
 9     @TableName varchar(max),
10     ----- 要查询的列名语句; 可空默认*
11     @ColumnName varchar(5000),
12     ----- 用来排序的列;  不可为空
13     @OrderByColumnName varchar(50),
14     ----- 排序desc(倒序5.4.3.2.1)或asc(正序1.2.3.4.5); 可空默认asc
15     @ShrtBy varchar(4),
16     ----- Where条件; 可空默认1=1
17     @Where varchar(5000),
18     ----- 每页显示数; 可空默认20
19     @PageShows int,
20     ----- 当前页数; 可空默认1
21     @CurrentPage int,
22     ----- 0为分页查询;其他为查询全部; 可空默认0
23     @IsPaging int
24 )
25 as
26 begin
27     ----- 参数检查及规范
28     if isnull(@Where,N‘‘)=N‘‘ set @Where = N1=1;
29     if isnull(@ColumnName,N‘‘)=N‘‘ set @ColumnName = N*;
30     if isnull(@PageShows,0)<1 set @PageShows = 20;
31     if isnull(@CurrentPage,0)<1 set @CurrentPage = 1;
32     if isnull(@ShrtBy,N‘‘)=N‘‘ set @ShrtBy = asc;
33     if isnull(@IsPaging,0)<>1 set @IsPaging = 0;
34     ----- 定义
35     -- 拼接的SQL语句
36     declare @SqlStr nvarchar(max);
37     declare @SqlWithStr nvarchar(max);
38     -- 开始条数
39     declare @StartIndex int;
40     -- 结束条数
41     declare @EndIndex int;
42     ----- 赋值
43     set @StartIndex = (@CurrentPage-1)*@PageShows+1;
44     print(@CurrentPage);
45     print(@PageShows);
46     print(@StartIndex);
47     set @EndIndex = @CurrentPage*@PageShows;
48     print(@EndIndex);
49     set @OrderByColumnName=@OrderByColumnName+ +@ShrtBy;
50     ----- 分页查询
51      set @SqlWithStr = Nwith temp as(select ROW_NUMBER() over(order by +@OrderByColumnName+N) as RowNumber,+@ColumnName+N from +@TableName+N as tableName where +@Where+N);
52     if(@IsPaging = 0)
53     begin
54         set @SqlStr = @SqlWithStr + N select +@ColumnName+N from temp where temp.RowNumber between +convert(nvarchar(20),@StartIndex)+N and +convert(nvarchar(20),@EndIndex)+N‘‘;
55         ---- print(@SqlStr);
56         exec(@SqlStr);
57         ----- 总数查询
58         set @SqlStr = @SqlWithStr + N select count(*) as TotalNumber from temp;
59         ---- print(@SqlStr);
60         exec(@SqlStr);
61     end
62     else
63     begin
64         set @SqlStr = @SqlWithStr + N select +@ColumnName+N from temp;
65         ---- print(@SqlStr);
66         exec(@SqlStr);
67     end
68 end

【原创】SQL分页查询存储过程