日期:2014-05-17 浏览次数:20917 次
CREATE PROCEDURE [SelectByPage] @pageSize int = 20, --分页大小 @currentPage int , --第几页 @columns varchar(1000) = '*', --需要得到的字段 @tableName varchar(100), --需要查询的表 @condition varchar(1000) = '', --查询条件, 不用加where关键字 @ascColumn varchar(100) = '', --排序的字段名 (即 order by column asc/desc) @bitOrderType bit = 0, --排序的类型 (0为升序,1为降序) @pkColumn varchar(50) = '', --主键名称 @TotalCount INT output -- 总记录数 AS BEGIN --存储过程开始 DECLARE @strTemp varchar(300) DECLARE @strSql varchar(5000) --该存储过程最后执行的语句 DECLARE @strOrderType varchar(1000) --排序类型语句 (order by column asc或者order by column desc) DECLARE @CountSql NVARCHAR(4000) print '' IF @condition !='' BEGIN SET @CountSql = 'SELECT @CountOUT=COUNT(*) FROM ' + @tableName + 'WHERE ' + @condition ; -- 拼接获取总记录数的 @CountSql 语句 end else BEGIN SET @CountSql = 'SELECT @CountOUT=COUNT(*) FROM ' + @tableName + @condition ; -- 拼接获取总记录数的 @CountSql 语句 end EXEC SP_EXECUTESQL @CountSql, N'@CountOUT INT OUT', @CountOUT = @TotalCount OUT; -- 获取总记录数 BEGIN IF @bitOrderType = 1 --降序 BEGIN SET @strOrderType = ' ORDER BY '+@ascColumn+' DESC' SET @strTemp = '<(SELECT min' END ELSE --升序 BEGIN SET @strOrderType = ' ORDER BY '+@ascColumn+' ASC' SET @strTemp = '>(SELECT max' END IF @currentPage = 1 --第一页 BEGIN IF @condition != '' SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+ ' WHERE '+@condition+@strOrderType ELSE SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+@strOrderType END ELSE -- **页 BEGIN IF @condition !='' SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+ ' WHERE '+@condition+' AND '+@pkColumn+@strTemp+'('+@pkColumn+')'+' FROM (SELECT TOP '+STR((@currentPage-1)*@pageSize)+ ' '+@pkColumn+' FROM '+@tableName + ' where '+@condition+@strOrderType+') AS TabTemp)'+@strOrderType ELSE SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+ ' WHERE '+@pkColumn+@strTemp+'('+@pkColumn+')'+' FROM (SELECT TOP '+STR((@currentPage-1)*@pageSize)+' '+@pkColumn+ ' FROM '+@tableName+@strOrderType+') AS TabTemp)'+@strOrderType END END print @strSql EXEC (@strSql) END GO
CREATE PROCEDURE [SelectByPage] @pageSize int = 20, --分页大小 @currentPage int , --第几页 @columns varchar(1000) = '*', --需要得到的字段 @tableName varchar(100), --需要查询的表 @condition varchar(1000) = '', --查询条件, 不用加where关键字 @ascColumn varchar(100) = '', --排序的字段名 (即 order by column asc/desc) @bitOrderType bit = 0,