以前參考過網上朋友(是誰忘了,知道的說一聲)寫的,但感覺有點不適合我的要求。修改大部分後如下所示。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最大值就行了