标签:
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
标签:
原文地址:http://www.cnblogs.com/xsj1989/p/4692782.html