Sql Server 分页四种写法

– 只做分页
–1.第一种
create proc MyPaging1
(
@pageIndex int,
@pageSize int,
@totalRecordCount int output
)
as
begin
select top (@pageSize) * from GoodsInfo where id not in (select top (@pageSize * (@PageIndex-1)) Id from GoodsInfo)
select @totalPageCount = Count(*) from GoodsInfo
end

go

–第2(只做分页)
create proc MyPaging2
(
@pageIndex int,
@pageSize int,
@totalPageCount int output
)
as
begin
–select top 5 * from GoodsInfo where id not in (select top 10 Id from GoodsInfo)
declare @s int ,@e int
set @s = @pageIndex * (@pageSize - 1)+1
set @e = @pageIndex * @pageSize

 select * from (select ROW_NUMBER() over (order by Id) as NO, * from GoodsInfo) T where T.NO between @s and @e

 declare @a decimal 
 select @a = Count(*) from GoodsInfo

 set @totalPageCount = CEILING( @a / @pageSize )
end
go

select * from GoodsInfo
declare @count int
exec MyPaging1 1,5,@count output
select @count
go

– 带固定查询条件的分页
create proc MyPaging3
(
@pageIndex int,
@pageSize int,
@Name varchar(50),
@price decimal,
@totalRecordCount int output
)
as
begin
select * into #Temp from GoodsInfo where Name like (%+@Name+%) and Price > @price
select top (@pageSize) * from #Temp where id not in (select top (@pageSize * (@PageIndex-1)) Id from #Temp)
select @totalRecordCount = Count(*) from #Temp
end

– 多个条件组合的分页 没看过用存储过程的
go
create proc MyPaging3
(
@pageIndex int,
@pageSize int,
@Name varchar(50),
@price decimal,
@totalRecordCount int output
)
as
begin
if len(@Name)=0 and @price =0
begin
select * into #Temp1 from GoodsInfo
select top (@pageSize) * from #Temp1 where id not in (select top (@pageSize * (@PageIndex-1)) Id from #Temp1)
select @totalRecordCount = Count() from #Temp1
end
else if len(@Name)=0 and @price>0
begin
select * into #Temp2 from GoodsInfo where price>@price
select top (@pageSize) * from #Temp2 where id not in (select top (@pageSize * (@PageIndex-1)) Id from #Temp2)
select @totalRecordCount = Count() from #Temp2
end
else if len(@Name)>0 and @price=0
begin
select * into #Temp3 from GoodsInfo where Name like (%+@Name+%)
select top (@pageSize) * from #Temp3 where id not in (select top (@pageSize * (@PageIndex-1)) Id from #Temp3)
select @totalRecordCount = Count() from #Temp3
end
else
begin
select * into #Temp4 from GoodsInfo where Name like (%+@Name+%) and Price>@price
select top (@pageSize) * from #Temp4 where id not in (select top (@pageSize * (@PageIndex-1)) Id from #Temp4)
select @totalRecordCount = Count() from #Temp4
end
end

declare @a int
exec MyPaging3 1,3,‘苹’,15,@a output
select @a
go
————————————————
版权声明:本文为CSDN博主「hyx。」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45244974/article/details/103575151
发布了43 篇原创文章 · 获赞 35 · 访问量 1560

猜你喜欢

转载自blog.csdn.net/qq_45244974/article/details/103594765