sqlServer2008版本不支持offset 分页,手动分页sql

该博客内容展示了如何使用Java实现一个名为`SqlServerPageUtil`的工具类,用于将SQL查询语句转化为支持分页的查询。类中包含了一个静态方法`convert`,该方法接收SQL查询、分页对象和主键字段作为参数,通过修改原始SQL,插入ROW_NUMBER()窗口函数来实现分页。方法首先根据`from`关键字拆分SQL,然后构建带有行号的子查询,并设置分页条件。此工具对于处理大量数据的分页显示非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import cn.hutool.db.Page;

public class SqlServerPageUtil {

    public static String convert(String sql, Page page, String primaryKey) {
        //一定要注意分页是从O页开始的
        //        Page page = new Page(0,2);
        //  sql = "select [spid] as 'SKU编码',[default_price] as '售价' from [t_item] ";
        // String sql2 = "select * FROM (select ROW_NUMBER()Over(order by id desc) as rowId,* from c_class) as t where rowId between 21 and 40";
        String[] str = sql.split("from", sql.length());
        String selectSQL = str[0];
        String fromSQL = " from ";
        String tableSQL = str[1];
        String modelSQL = " (select ROW_NUMBER()Over(order by " + primaryKey + " desc ) as rowId,* from " + tableSQL + " ) as t ";
        String whereSQL = "where rowId between " + (page.getPageSize() * page.getPageNumber() + 1) + " and " + (page.getPageSize() * page.getPageNumber() + page.getPageSize());
        String exeSql = selectSQL + fromSQL + modelSQL + whereSQL;
        return exeSql;
        //System.out.println(exeSql);
    }
//    public static void main(String[] args) {
//    String         sql = "select [spid] as 'SKU编码',[default_price] as '售价' from [t_item] ";

//        Page page = new Page(0,2);
//        convert(sql,page,"id");
//    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值