1 . 首先要获取记录总数
-- =============================================
-- Description:查询字段总记录数集合(通用存储过程)
-- =============================================
create procedure DZ_Count
@Keyfield varchar(30), --主键
@TableName varchar(30),--表名
@strWhere VARCHAR(1500) --查询条件,不包括where字符
as
exec('select count(' + @Keyfield +') from ['+ @TableName +'] Where ' + @strWhere +'' )
go
2 . 分页获取记录
-- =============================================
-- Description:查询分页集合(通用存储过程)
-- =============================================
CREATE PROCEDURE UP_GetCollectionPage
(
@tblName VARCHAR(255), -- 表名
@strGetFields VARCHAR(1000) = '*', -- 需要返回的列
@fldName VARCHAR(255)='', -- 排序的字段名
@PageSize INT = 10, -- 页尺寸
@PageIndex INT = 1, -- 页码
@doCount BIT = 0, -- 返回记录总数, 非 0 值则返回
@OrderType BIT = 0, -- 设置排序类型, 非 0 值则降序
@strWhere VARCHAR(1500) = '' -- 查询条件 (注意: 不要加 WHERE)
)
AS
SET NOCOUNT ON
DECLARE @strSQL VARCHAR(5000) -- 主语句
DECLARE @strTmp VARCHAR(110) -- 临时变量
DECLARE @strOrder VARCHAR(400) -- 排序类型
IF(@doCount != 0)
BEGIN
IF @strWhere !=''
SET @strSQL = 'SELECT COUNT(1) AS Total FROM [' + @tblName + '] WHERE '+@strWhere
ELSE
SET @strSQL = 'SELECT COUNT(1) AS Total FROM [' + @tblName + ']'
END
--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都是@doCount为0的情况
ELSE
BEGIN
IF @OrderType != 0
BEGIN
SET @strTmp = '<(SELECT MIN'
SET @strOrder = ' ORDER BY [' + @fldName +'] DESC'
--如果@OrderType不是0,就执行降序,这句很重要
END
ELSE
BEGIN
SET @strTmp = '>(SELECT MAX'
SET @strOrder = ' ORDER BY [' + @fldName +'] ASC'
END
IF @PageIndex = 1
BEGIN
IF @strWhere != ''
SET @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM [' + @tblName + '] WHERE ' + @strWhere + ' ' + @strOrder
ELSE
SET @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' FROM ['+ @tblName + '] '+ @strOrder
--如果是第一页就执行以上代码,这样会加快执行速度
END
ELSE
BEGIN
--以下代码赋予了@strSQL以真正执行的SQL代码
SET @strSQL = 'SELECT TOP ' + str(@PageSize) +' '+@strGetFields+ ' 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) +' '+@strGetFields+ ' FROM ['
+ @tblName + '] WHERE [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) FROM (SELECT TOP ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] FROM [' + @tblName + '] WHERE ' + @strWhere + ' '
+ @strOrder + ') AS tblTmp) AND ' + @strWhere + ' ' + @strOrder
END
END
EXEC (@strSQL)
SET NOCOUNT OFF
GO