码迷,mamicode.com
首页 > 数据库 > 详细

sql分页存储过程

时间:2015-07-31 20:08:59      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

USE [DBName]
GO
/****** Object: StoredProcedure [dbo].[UP_GetRecordByPage] Script Date: 12/05/2012 16:17:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[UP_GetRecordByPage]
@tblName varchar(255), -- 表名
@fldName varchar(255), -- 主键字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@RowCount int output, -- 返回记录总数
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere varchar(1000) = ‘‘ -- 查询条件 (注意: 不要加 where)
AS

declare @strSQL varchar(6000) -- 主语句
declare @strTmp varchar(100) -- 临时变量
declare @strOrder varchar(400) -- 排序类型

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) + ‘ [‘
+ @fldName + ‘] 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) + ‘ [‘
+ @fldName + ‘] 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

declare @sql NVARCHAR(400)

set @sql = N‘select @RowCount=count(*) from ‘+@tblName+‘ where ‘+ @strWhere
EXEC sp_executesql @sql,N‘@RowCount int OUT‘,@RowCount OUT

exec (@strSQL)

GO

 

第二种:


if exists(select * from sys.objects where name=‘proc_GetRecordByPages‘)
drop proc proc_GetRecordByPages
go
create procedure proc_GetRecordByPages
@PageIndex int=1,
@PageSize int=10,
@PageCount int=1 output
as
declare @StartIndex int,@EndIndex int
set @StartIndex=(@PageIndex-1)*@PageSize+1
set @EndIndex=@PageIndex * @PageSize
select * from
(
select ROW_NUMBER()over(order by p_order asc) as sno,* from App_Product
) as tb1
where sno between @StartIndex and @EndIndex
set @PageCount = (select COUNT(1) from App_Product)
go

declare @PageCount int
exec proc_GetRecordByPages 1,20,@PageCount output
select @PageCount

 

sql分页存储过程

标签:

原文地址:http://www.cnblogs.com/xsj1989/p/4692782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!