MS SQL Server分页通用存储过程(获取每一页和记录总数)

/*The store produce must need main ID,
It can get record of each page and the count of record,
You can get two ResultSet use by getMoreElement() in java*/
CREATE PROCEDURE GetPageRecordAndCount(
 @tblName      NVARCHAR(255),       -- 表名
 @id       NVARCHAR(255),   -- 主键ID
 @fldName      NVARCHAR(255),       -- 字段名,用来排序
 @PageSize     int = 10,           -- 页尺寸
 @PageIndex    int = 1,            -- 页码
 @OrderType    bit = 0,            -- 设置排序类型, 非 0 值则降序
 @strWhere     NVARCHAR(1000) = ''  -- 查询条件 (注意: 不要加 where)
)AS

declare @strSQL   NVARCHAR(1000)     -- 主语句
declare @strTmp   NVARCHAR(300)      -- 临时变量
declare @strOrder NVARCHAR(400)      -- 排序类型

if @OrderType != 0
begin
    set @strTmp = 'NOT IN'
    set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
    set @strTmp = 'NOT IN'
    set @strOrder = ' order by [' + @fldName +'] asc'
end

--SELECT TOP 5 * FROM tb_productInfo WHERE productId NOT IN(SELECT TOP 5 productId FROM tb_productInfo ORDER BY productName) ORDER BY productName

set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
    + @tblName + '] where [' + @id + ']' + @strTmp + ' (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @id + '] from [' + @tblName + ']' + @strOrder + ' )'
    + @strOrder

if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + '] where [' + @id + ']' + @strTmp + ' (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @id + '] from [' + @tblName + '] where (' + @strWhere + ') '
        + @strOrder + ')  and (' + @strWhere + ') ' + @strOrder

if @PageIndex = 1
begin
    set @strTmp = ''
    if @strWhere != ''
        set @strTmp = ' where (' + @strWhere + ')'

    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end
exec (@strSQL)

set @strSQL = 'select count(*) as Total from [' + @tblName + ']'
if @strWhere != ''
BEGIN
set @strSQL = 'select count(*) as Total from [' + @tblName + '] WHERE '+@strWhere
END

exec (@strSQL)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值