日期:2014-05-17  浏览次数:20732 次

求在mysql中用limit,在sqlserver中用top的问题??急急急
以前是用mysql写得,分页,可以实现效果,但是现在想要sqlserver数据库,不知道怎么总是报错,求教??
将sql改为String sql = "select top "+pageSize+" * from stu where id not in(select top "+pageSize*(pageIndex-1)+" id from stu)";总是报一些莫名其妙的错误,求大神,告诉我改怎么做。。


//dao类
public Map stuSelect(int pageIndex,int pageSize) throws Exception{

Map map = new HashMap();
List<StuInfo> list = new ArrayList<StuInfo>();

String sql = "select * from stu where 1=1";
sql += " order by id limit "+((pageIndex-1)*pageSize)+","+pageSize+"";
 
//String sql = "select top "+pageSize+" * from stu where id not in(select top "+pageSize*(pageIndex-1)+" id from stu)";

System.out.println(sql);

StuInfo info = null;

Connection con = this.getCon();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);

while(rs.next()){
info = new StuInfo();
info.setId(rs.getInt("id"));
info.setName(rs.getString("name"));
info.setAge(rs.getInt("age"));
list.add(info);
}
map.put("list", list);

map.put("totalSize", this.getTotalCnt(sql));

this.Close(con, st, rs);
return map;

}

//BaseDao类

public int getTotalCnt(String sql) throws Exception{

StringBuffer cntSql = new StringBuffer("select count(*) ");
String sqlold = sql.substring(sql.indexOf("from"),sql.indexOf("limit")); //去除分页
cntSql.append(sqlold);

int count = 0;
Connection con = this.getCon();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(cntSql.toString());
if(rs.next())
count = rs.getInt(1);
else 
count = 0;
this.Close(con, st, rs);
return count;

}




------解决方案--------------------
"select top "+pagesize+" * from table as t1 where (ID not in (select top "+pagesize*(pageindex-1)+" t2.ID from table as t2 order by ID desc))order by ID desc";
 

------解决方案--------------------
String sql = "select top "+pageSize+" * from stu where id not in(select top "+pageSize*(pageIndex-1)+" id from stu)";