sqlserver存储过程分页查询_sql server分页查询

sqlserver存储过程分页查询_sql server分页查询sqlserver 单表(视图)通用分页存储过程 create procedure proc_getpage @table_name varchar(100), –表名(视图) @select_fi

sqlserver 单表(视图)通用分页存储过程

create procedure proc_getpage
@table_name varchar(100),              --表名(视图)
@select_fields varchar(1000)=" * ",    --需要返回的列
@page_size int=10,                     --页尺寸,如果为0则表示返回所有行,不分页
@page_index int=1,                     --页码
@sort_field varchar(50)="",            --排序字段 
@order_type nvarchar(10)="desc",       --排序类型, asc|desc
@str_where varchar(max)=""             --查询条件(注意: 不要加 where)
as
begin
    declare @select_sql varchar(max)       --主语句
    declare @count_sql varchar(max)        --获取总记录数语句
    declare @order_sql varchar(400)        --排序子语句

    if(@str_where!="")
    begin
        set @count_sql="select count(*) as total from " + @table_name + " where " + @str_where
    end
    else
    begin
        set @count_sql="select count(*) as total from " + @table_name
    end

    set @order_sql=" order by " + @sort_field + " " + @order_type

    if(@page_size=0)
    begin
        if(@str_where!="") 
        begin
            set @select_sql="select " + @select_fields + " from " + @table_name + " where " + @str_where + " " + @order_sql
        end
        else
        begin
            set @select_sql="select " + @select_fields + " from " + @table_name + " " + @order_sql
        end
    end 
    else 
    begin
        set @select_sql="select * from (select row_number() over(" + @order_sql + ") as rowNo," + @select_fields + " from " + @table_name
        
        if(@str_where!="")
        begin
            set @select_sql+=" where " + @str_where
        end

        set @select_sql+=") as " + @table_name + " where rowNo between " + cast(((@page_index-1)*@page_size+1) as varchar) + " and " + cast((@page_index*@page_size) as varchar)
    end 
    
    exec(@count_sql)
    exec(@select_sql)
end

代码100分

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/10876.html

(0)
上一篇 2022-12-20
下一篇 2022-12-20

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注