Urggggg! I\'ve been struggling with this for a long time! I can do it with MySQL so easy but not with SQL Server :(
Here are the simplified tables which should be jo
I liked Taha Siddiqui's answer except that it requires modifying the passed in query and it didn't work for an SQL UNION statement that I have to use due to some very poor design decisions made by a former co-worker.
The generic SQL Server query is:
SELECT * FROM (
select ROW_NUMBER() OVER (order by ID) as row_num, * FROM (
<>
) AS tempTable1
) AS tempTable2 WHERE row_num >= ((pageNum -1) * pageSize) AND row_num < ((pageNum -1) * pageSize) + pageSize;
I created a Java function that assumes one-based paging:
public static String buildPagingQuery(String sqlStr, String sortExpression, int pageNum, int pageSize) {
if (StringUtils.isBlank(sortExpression)) { //NOTE: uses org.apache.commons.lang.StringUtils
sortExpression = " (select 0)";
}
int startIndex = ((pageNum - 1) * pageSize) + 1;
int endIndex = startIndex + pageSize;
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM (");
sb.append("SELECT ROW_NUMBER() OVER (ORDER BY ");
sb.append(sortExpression);
sb.append(") as row_num, * FROM (");
sb.append(sqlStr);
sb.append(") as tempTable1 ");
sb.append(") AS tempTable2 ");
sb.append("WHERE row_num >= ").append(startIndex);
sb.append(" AND row_num < ").append(endIndex);
return sb.toString();
}
I have not yet checked performance on a large table.