sql通用分页自定义表条件存储过程

create PROCEDURE PrcTestByPage 
(
 @tablename varchar(50),                                
 @selectfilter varchar(100),       
 @orderbyfilter varchar(100),                          
 @selectpage int,                      
 @pageSize int                             
)
AS 
BEGIN -- 存储过程开始 

declare @pkname varchar(100)  -- 获取表的主键名称
SELECT @pkname=COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME=@tablename

declare @num int
set @num=(@selectpage-1)*@pageSize

declare @strsqltwo varchar(4000)
set @strsqltwo='select top '+STR(@num)+' '+@pkname+' from '+@tablename
DECLARE @strSql varchar(4000)           --SQL执行语句
set @strSql='select top '+str(@pageSize)+' * from '+@tablename

if(len(@selectfilter)>0)   -- 判断有没有where条件 
BEGIN 
 set @strsqltwo=@strsqltwo+' where '+@selectfilter
    SET @strSql = @strSql+' where '+@selectfilter+' and '+@pkname+' not in('+@strsqltwo+')'    
END 
else
 SET @strSql = @strSql+' where '+@pkname+' not in('+@strsqltwo+')'
if(len(@orderbyfilter)>0) --判断有没有排序条件
BEGIN 
 set @strsqltwo=@strsqltwo+' order by '+@orderbyfilter
    SET @strSql = @strSql+' order by '+@orderbyfilter    
END 

EXEC (@strSql) 
END  -- 存储过程结束 

GO  

exec PrcTestByPage 'Print_order','','',2,6

  

posted @ 2015-08-27 08:14  每天进步一点点!  阅读(256)  评论(0编辑  收藏  举报