SQL Server 存储过程query(分页功能)

-----------------分页存储过程------------------------------------
--返回数据列表和总行数
alter proc demo_stu_info_search
@startIndex int,
@numRows int,
@key varchar(100)
as
-- 定义变量区
-- 创建分页临时表(自增主键,数据表ID)
declare @TPage table(pageIndex int Identity(0,1), Id varchar(20))
declare @TotalCount int
--业务逻辑处理区
begin
	if @startIndex is null or @startIndex = ''
		set @startIndex = 0
        --往临时表中添加数据
	insert into @TPage(Id)
	select stu_id 
	from stu 
	where name like '%' + @key + '%'
	order by stu_id asc
	--受影响的记录行
	set @TotalCount = @@ROWCOUNT
	--分页查询(关联临时表)
	select s.stu_id, s.name, s.age
	from @TPage t inner join stu s on t.Id = s.stu_id
	where 1= 1
		and t.pageIndex >= @startIndex 
		and t.pageIndex < @startIndex + @numRows 
		and name like '%' +@key+ '%'
	order by stu_id asc
	
	return @TotalCount
end
--执行存储过程
exec demo_stu_info_search 3, 2, '张'


备注:本人QQ:251693481,欢迎大家一起交流。

猜你喜欢

转载自huangliangbao.iteye.com/blog/2267971