分页的存储过程
例子:
ALTER PROCEDURE [dbo].[Proc_GetCarriersByPage]
@pageIndex INT , --第几页
@pageSize INT , --每页展示的数据条数
@state int=0, --承运单的状态值
@ReviveDateStart datetime null, --接受时间开始 例如:6月
@ReviceDateEnd datetime null, --接收时间结束 例如:12月
@totalCount INT OUTPUT --数据总条数
AS
BEGIN
declare @sql nvarchar(1024); --设置sql方便后面赋值处理
declare @whereStr nvarchar(512);
set @whereStr='';
--0、拼接条件
if @state>0
begin
set @whereStr=@whereStr+' and FinishedState='+CONVERT(nvarchar(32),@state);
end
if @ReviveDateStart is not null and @ReviveDateStart<>''
begin
set @whereStr=@whereStr+' and LeaverDate>'''+CONVERT(nvarchar(32),@ReviveDateStart)+'''';
end
if @ReviceDateEnd is not null and @ReviceDateEnd<>''
begin
set @whereStr=@whereStr+' and LeaverDate<='''+CONVERT(nvarchar(32),@ReviceDateEnd)+'''';
end
--1、获取查询数据的总条数
set @sql='select @rowCount=count(*) from Carriers c
inner join Scheduling s on c.CarriersID=s.FK_CarriersID
inner join [User] u on c.FK_UserID=u.UserID where c.IsDelete=0 and c.FinishedState>1'+@whereStr;
exec sys.sp_executesql @sql,N'@rowCount int output',@totalCount output;
--2.1、判断传入的页码是否小于1
IF @pageIndex<1
BEGIN
set @pageIndex=1;
END
--2.2、判断传入的页码是否大于最大页码
declare @pageMax int;
set @pageMax=ceiling(convert(float,@totalCount)/@pageSize)
IF @pageIndex>@pageMax
BEGIN
set @pageIndex=@pageMax
END
--3、获取该页码的数据
set @sql='select * from
(select ROW_NUMBER() OVER(order by CarriersID) as rowIndex,c.SendCompany,u.UserName,c.CarriersID,c.LeaverDate,c.TotalCost from Carriers c
inner join Scheduling s on c.CarriersID=s.FK_CarriersID
inner join [User] u on u.UserID=c.FK_UserID where c.IsDelete=0 and c.FinishedState>1'+@whereStr+' ) as temp
where temp.rowIndex between '+CONVERT(nvarchar(50),(@pageIndex-1)*@pageSize+1)+' and '+CONVERT(nvarchar(50),@pageIndex*@pageSize)
exec sys.sp_executesql @sql;
print @sql;
END