SqlServer通用存储过程(1)-千万级数据库高速分页显示 - ASP.NET Forums - 已使用 Google 工具栏发送

0 views
Skip to first unread message

ibar 莫非

unread,
Aug 18, 2006, 5:49:27 PM8/18/06
to ea...@googlegroups.com
SqlServer通用存储过程(1)-千万级数据库高速分页显示 - ASP.NET Forums


改一下,看看这样是不是更好一点?
/*
  函数名称: GetRecordFromPage
  函数功能: 获取指定页的数据
  参数说明:   @tblName        包含数据的表名
             @fldName        关键字段名
              @PageSize      每页记录数
             @PageIndex    要获取的页码
              @IsCount         是否要取得记录数
             @OrderType    排序类型, 0 - 升序, 1 - 降序
             @strWhere      查询条件 (注意: 不要加 where)
*/
CREATE  PROCEDURE pGO_GetRecordFromPage
    @tblName      varchar(255),       -- 表名
    @fldName      varchar(255),       -- 字段名
    @PageSize     int = 10,           -- 页尺寸
    @PageIndex    int = 1,            -- 页码
    @IsCount      bit = 0,            -- 返回记录总数, 非 0 值则返回
    @OrderType    bit = 0,            -- 设置排序类型, 非 0 值则降序
    @strWhere     varchar(1000) = ''  -- 查询条件 (注意: 不要加 where)
AS

declare @strSQL   varchar(6000)       -- 主语句
declare @strTmp   varchar(500)        -- 临时变量
declare @strOrder varchar(400)        -- 排序类型

-- 如果是查询记录总数,直接使用Count(0)函数
if @IsCount != 0
 begin
  if @strWhere != ''
   set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere
  else
   set @strSQL = 'select count(*) as Total from [' + @tblName + '] '
 end
--如果是想查询记录,则
else
 begin
  if @PageIndex = 1
   begin
        set @strTmp = ''
        if @strWhere != ''
             set @strTmp = ' where ' + @strWhere

        set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
             + @tblName + ']' + @strTmp + ' ' + @strOrder
   end
  else
   begin
    --如果是降序查询……
    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

    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
    else
     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  

  
   end
end

exec (@strSQL)
GO


Reply all
Reply to author
Forward
0 new messages