以前参考过网上朋友(是谁忘了,知道的说一声)写的,但感觉有点不适合我的要求。修改大部分后如下所示。GetRecordPageTotal为分页时取得页总数。当然可以写在GetRecordByPage里,但个人认为那样的话,在只取页总数的情况下也要使用GetRecordByPage,查询效率不太好,就分开写
--///
if exists (select * from sysobjects where id = object_id('GetRecordPageTotal')and type = 'P')
drop procedure GetRecordPageTotal
go
if exists (select * from sysobjects where id = object_id('PgetRecordByPage')and type = 'P')
drop procedure PgetRecordByPage
go
--///
create procedure GetRecordPageTotal
@tblName varchar(100), -- 表名
-- @PageSize int, -- 页大小
@strWhere varchar(1000) = '' -- 查询条件 (注意: 不要加 where)
as
begin
declare @strSqlTemp varchar(2000) -- 临时变量
if @strWhere=''
set @strSqlTemp='select count(*) from ['+@tblName+']'
else set @strSqlTemp='select count(*) from ['+@tblName+'] where '+@strWhere
exec (@strSqlTemp)
end
GO
--
create procedure GetRecordByPage
@tblName varchar(100), -- 表名
@fldCow varchar(100)='*', -- 要查询的列
@fldName varchar(255), -- 排序列
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@OrderType bit = 1, -- 设置排序类型, 1则降序
@strWhere varchar(2000) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL varchar(3000) -- 主语句
declare @strTmp varchar(1000) -- 临时变量
declare @strOrder varchar(500) -- 排序类型
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) + ' '+@fldCow+' 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) + ' '+@fldCow+ ' 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) + ' '+@fldCow+ ' from ['
+ @tblName + ']' + @strTmp + ' ' + @strOrder
end
exec (@strSQL)
GO
注:不想分页的话,把PageSize 值设到int最大值就行了