分页存储过程,可将查询条件作为参数传递的分页查询存储过程

 
ALTER PROCEDURE PR_ArticleList
 
     @index int,                               --页索引
     @pagesize int,                            --页大小
     @condition nvarchar(1000)            --查询条件字符串
    
    
AS
 
declare @starID varchar(20)               --起始ID
declare @rowcount int                    --要查询记录数
declare @count int                        --记录总数
declare @maxpages int                    --总页数
declare @Tem nvarchar(2000)               --字查询模板
 
     SET NOCOUNT ON
    
    
     --当存在查询条件,在查询条件前加AND
     if(LEN(@condition)>0)
         set @condition = 'and '+@condition
    
     --查询出符合条件的记录总数
     select @Tem='select @count=count(*) from [Articles] where 1=1'+ @condition
     execute sp_executesql
              @Tem,
              N'@count int OUTPUT',
              @count output
    
     --计算记录数可分为多少页
     set @maxpages = (@count+@pagesize-1)/@pagesize
    
     --当页索引大于最大页索引,设置页索引为最大页索引 最大页索引=总页数-1
     if(@index+1>=@maxpages)
         set @index=@maxpages-1
        
     --当计算出来的页索引为负,设置页索引为
     if(@index<0)
         set @index=0
        
     --计算当前页索引页的第一条记录是第几条
     set @rowcount = @index*@pagesize+1
    
     --设置查询影响行数
     set rowcount @rowcount
    
     --查询当前索引页的第一条记录的ID并附给@starID
     select @Tem = 'select @starID=ArticleID from [Articles] where 1=1 '+@condition+' order by ArticleID desc '
     execute sp_executesql
              @Tem,
              N'@starID varchar(20) OUTPUT',
              @starID output
    
    
     --设置查询影响行数
     set rowcount @pagesize
    
     select @Tem = 'select * from [Articles] where ArticleID<='+@starID + @condition+ ' order by ArticleID desc '
     execute sp_executesql
         @Tem
        
        
     Set NOCOUNT OFF
    
     --返回当前条件下总记录数
     RETURN @count
    

另外,需要说明一下,很多朋友问到 N 是什么意思!

N 在这里表示 Unicode,就是双字节字符。对于西文字符,用一个字节来存储过足够了,对于东方文字字符,就需要两个字节来存储。Unicode 为了统一、规范、方便、兼容,就规定西文字符也用两个字节来存储。

在GOOGLE上搜索 SQL N 就可以找到很多相关的信息了!

原文地址:https://www.cnblogs.com/ZetaChow/p/2237375.html