分页Sql语句

时间:2023-03-09 18:42:26
分页Sql语句

第一种 Top剔除法。去除Top (pageIndex-1)*PageSize

SELECT  TOP 10* FROM dbo.SBD_EXCHANGE_BILL
WHERE EB_ID NOT IN (SELECT TOP (10*1) EB_ID FROM dbo.SBD_EXCHANGE_BILL ORDER BY EB_ID)

第二种 Max剔除法 。去除 小于  Max(PageIndex-1)*pageSize

SELECT TOP 10 * FROM dbo.SBD_EXCHANGE_BILL
WHERE EB_ID >(SELECT MAX(EB_ID)
FROM (SELECT TOP (10*2) EB_ID FROM dbo.SBD_EXCHANGE_BILL ORDER BY EB_ID) AS T )

第三种方法 游标法(来自网络)

CREATE  PROCEDURE pGo_GetRecordFromPage
@tblName varchar(255), -- 表名
@fldName varchar(255), -- 字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@IsCount bit = 0, -- 返回记录总数, 非 0 值则返回
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere varchar(1000) = '' -- 查询条件 (注意: 不要加 where)
AS declare @strSQL varchar(6000) -- 主语句
declare @strTmp varchar(500) -- 临时变量
declare @strOrder varchar(400) -- 排序类型
if @IsCount != 0 -- 假如是查询记录总数,直接应用Count(0)函数
begin
if @strWhere != ''
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere
else
set @strSQL = 'select count(*) as Total from [' + @tblName + '] '
end
--假如是想查询记载,则
else
begin
if @PageIndex = 1 --如果是第一页
begin
set @strTmp = ''
if @strWhere != ''
set @strTmp = ' where ' + @strWhere set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + ']' + @strTmp + ' ' + @strOrder
end else --如果不是第一页
begin
--假如是降序查询……
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
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
+ @strOrder
end
end exec (@strSQL)
GO

存储过程

执行存储过程

USE [student]
GO DECLARE @return_value int --声明返回值变量 EXEC @return_value = [dbo].[pGO_GetRecordFromPage] --返回值等于存储过程返回结果
@tblName = N'T_StuInfo', --指定表名
@fldName = N'stuid', --指定排序的字段
@PageSize = 4, --分页大小
@PageIndex = 2, --页码
@IsCount =0, --是否返回记录总数,当指定1时返回满足strWhere条件的记录总数
@OrderType = 0, --排序类型0升1降序
@strWhere =" " --where条件,不用写where SELECT 'Return Value' = @return_value GO

执行存储过程