CREATE PROCEDURE [dbo].[GetRecordByPager]
@tblName varchar(255), -- 表名
@fldName varchar(255), -- 主键字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@IsReCount bit = 0, -- 返回记录总数, 非 0 值则返回
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere varchar(1000) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL varchar(6000) -- 主语句
declare @strTmp varchar(2000) -- 临时变量
declare @strOrder varchar(800) -- 排序类型
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
if @IsReCount != 0
begin
if @strWhere != ''
begin
set @strSQL = 'SELECT COUNT(1) AS Total FROM [' + @tblName + ']'+' WHERE ' + @strWhere
end
else
begin
set @strSQL = 'SELECT COUNT(1) AS Total FROM [' + @tblName + ']'
end
end
print @strSQL
exec (@strSQL)
每当看到有人装逼的时候,哥总是低着头,不是哥有涵养,哥是在找砖头.....