---
title: "jdbc CallableStatement 存储过程 实现 SQL SERVER分页"
author: "GH0769"
date: "2010-05-24T16:02:53Z"
tags: []
categories: ["编程语言"]
slug: "jdbc-callablestatement-sql-server"
draft: false
lastmod: "2010-05-24T16:02:53Z"
id: 673963
url: "https://gh0769.iteye.com/blog/673963"
---

SQL Server的分页可以有几种方式实现，例如最简单的：

1、select top 20 * from table where id not in(select top 200 id from table where ?)即取20条记录，并且这些记录是不在当前页的之前的那些页的记录中。这个方式比较简单，但破坏SQL的可读性，并且当你的该SQL语句有很多的过滤条件时，显得特别恶心了，例如 select top pagesize from table where id not in(select top pagesize * (curPage - 1) id from table where create\_date &gt; 'aaaa' and create\_date &lt; 'aaaaa' and....) and create\_date &gt; 'aaaa' and create\_date &lt; 'aaaaa' and.......。如果你的程序本身已经已经有了大量的JDBC操作sql语句，那现在突然让你加一个分页的功能，。

2、用后台SQL SERVER的存储过程来实现分页：

CREATE procedure pageProcedure  
@sqlstr nvarchar(4000), --查询字符串  
@currentpage int, --第N页  
@pagesize int, --每页行数  
@out\_row\_count int output,--输出总行数  
@out\_page\_count int output--输出总页数  
as  
set nocount on  
declare @P1 int, --P1是游标的id  
@rowcount int  
exec sp\_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output  
\--select ceiling(1.0\*@rowcount/@pagesize) as 总页数,@rowcount as 总行数,@currentpage as 当前页

set @out\_row\_count = @rowcount  
set @out\_page\_count = ceiling(1.0\*@rowcount/@pagesize)

set @currentpage=(@currentpage-1)\*@pagesize+1  
exec sp\_cursorfetch @P1,16,@currentpage,@pagesize  
exec sp\_cursorclose @P1  
set nocount off  
GO

 

调用

declare @row\_count int

declare @page\_count int

exec pageProcedure 'select * from employees', 1, 200, @row\_count, @page\_count

 

现在看如果我们用JDBC如何读取返回的数据：

CallableStatement callableStatement = this.getDatabase().getConnection().prepareCall("{call pageProcedure(?,?,?,?,?)}");  
            callableStatement.setString(1, this.getCurSQL());//IN  
            callableStatement.setInt(2, this.curPage);//IN  
            callableStatement.setInt(3, this.countPerPage); //IN  
             
            callableStatement.registerOutParameter(4, Types.INTEGER);//OUT  
            callableStatement.registerOutParameter(5, Types.INTEGER);         //OUT    
            callableStatement.execute();  
            int r = 0;

//返回ResultSet  
            while(callableStatement.getMoreResults())  
            {  
                ResultSet set = callableStatement.getResultSet();  
                if(set != null)  
                {

                   //处理ResultSet 又回到原来的处理模式，如果这一块包装的话，对原来的代码影响小，  
                   set.close();  
                }                 
                 
            }

这里的情况是如果有大量的这样sql语句的时候，这种模式对代码的修改比较少。如果较少的就不说。