数据库
首页 > 数据库> > sqlserver分页存储过程

sqlserver分页存储过程

作者:互联网

先来张测试执行分页存储过程的图片:
在这里插入图片描述
分页存储过程如下:

USE [数据库名,如:Table1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Description: <支持联合主键分页...>
-- =============================================
ALTER PROCEDURE [dbo].[GetRecordByPage]
    @tblName      varchar(255),       -- 表名
    @fldName      varchar(255),       -- 字段名
    @PageSize     int = 10,           -- 页尺寸
    @PageIndex    int = 1,            -- 页码
    @OrderType    bit = 0,            -- 设置排序类型, 非 0 值则降序
	@IsReCount    bit = 0,            -- 是否返回总记录数, 非 0 值则返回
	@TotalCount   int = 0 output,     -- 总记录数
	@TotalPage    int = 0 output,     -- 总页数
    @strWhere     varchar(1000) = ''  -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL   nvarchar(1000)       -- 主语句
declare @SqlCount nvarchar(1000)       -- 统计语句	
declare @strTmp   varchar(1000)        -- 临时变量
declare @strOrder varchar(400)        -- 排序类型
declare @orderField varchar(255)       -- 排序字段

set @orderField=REPLACE(@fldName,'+',',')

if @OrderType != 0
begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by [' + @fldName +'] asc'
end

set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
    + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
    + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @orderField + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
    + @strOrder

if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
        + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @orderField + '] from [' + @tblName + '] where ' + @strWhere + ' '
        + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

if @PageIndex = 1
begin
    set @strTmp =''
    if @strWhere != ''
        set @strTmp = ' where ' + @strWhere

    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end

if @IsReCount!=0
    set @strTmp =''
    if @strWhere != ''
        set @strTmp = ' where ' + @strWhere	
	set @SqlCount = 'select @TotalCount=count(*),@TotalPage=CEILING((COUNT(*)+0.0)/'+ CAST(@PageSize AS VARCHAR)+') from [' + @tblName + ']'+ @strTmp+''
	EXEC sp_executesql @SqlCount,N'@TotalCount INT OUTPUT,@TotalPage INT OUTPUT',@TotalCount OUTPUT,@TotalPage OUTPUT


exec (@strSQL)

标签:存储,set,tblName,分页,--,strWhere,sqlserver,strTmp,select
来源: https://blog.csdn.net/CGS_______/article/details/115083624