自己常用的分页SQL

1.
   Select Top PageSize * From Table where biaoshi not in (Select Top (PageIndex-1)*PageSize biaoshi From Table )

2.
CREATE PROCEDURE [dbo].[UP_Common_Pager](
 @tblName   nvarchar(255),       -- 表名
 @Fields nvarchar(1000) = '*',  -- 需要返回的列
 @OrderField nvarchar(255)='',      -- 排序的字段名
 @PageSize   int = 10,          -- 页尺寸
 @PageIndex  int = 1,           -- 页码
 @doCount  bit = 0,   -- 返回记录总数, 非 0 值则返回
 @OrderType bit = 1,  -- 设置排序类型, 非 0 值则降序
 @strWhere  nvarchar(1500) = '',  -- 查询条件 (注意: 不要加 where)
 @sql nvarchar(4000)='' out
)AS
begin
 if @pageIndex=0
  set  @pageIndex=1
 declare @strSQL   nvarchar(4000)       -- 主语句
 declare @strTmp   nvarchar(110)        -- 临时变量
 declare @strOrder nvarchar(400)        -- 排序类型
 if @doCount != 0
  begin
   if @strWhere !=''
    set @strSQL = 'select count(*) as Total from ' + @tblName + ' where ' + @strWhere
   else
    set @strSQL = 'select count(*) as Total from ' + @tblName + ''
  end 
 --以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都是@doCount为0的情况
 else
  begin
   if @OrderType != 0
    begin
     set @strTmp = '<(select min'
     set @strOrder = ' order by ' + @OrderField +' desc'
     --如果@OrderType不是0,就执行降序,这句很重要!
    end
   else
    begin
     set @strTmp = '>(select max'
     set @strOrder = ' order by ' + @OrderField +' asc'
    end
   if @PageIndex = 1
    begin
     if @strWhere != ''  
      set @strSQL = 'select top ' + str(@PageSize) +' '+@Fields+ '  from ' + @tblName + ' where ' + @strWhere + ' ' + @strOrder
     else
      set @strSQL = 'select top ' + str(@PageSize) +' '+@Fields+ '  from '+ @tblName + ' '+ @strOrder
    end
   else
    begin
     set @strSQL = 'select top ' + str(@PageSize) +' '+@Fields+ '  from '+ @tblName + ' where [' + @OrderField + ']' + @strTmp + '(['+ @OrderField + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @OrderField + '] from ' + @tblName + '' + @strOrder + ') as tblTmp)'+ @strOrder
     if @strWhere != ''
      set @strSQL = 'select top ' + str(@PageSize) +' '+@Fields+ '  from '+ @tblName + ' where [' + @OrderField + ']' + @strTmp + '(['+ @OrderField + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @OrderField + '] from ' + @tblName + ' where ' + @strWhere + ' '+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
    end
  end
 set @sql=@strSql
 exec (@strSQL)
end

你可能感兴趣的:(sql)