doushan1850 2019-03-28 09:46
浏览 65
已采纳

服务器端处理数据表分页Microsoft SQL

Im trying to setup pagination with datatables using PHP PDO with MS SQL, since "limit" is not applicable i find it really hard to make the code work.

I have tried the "TOP" syntax but it will only filter the specified number and the pagination wont work.

I have tried offset and fetch still not working.

These is the working code when Mysql is used and its so easy to understand and perform.

if($_POST["length"] != -1)
   {
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
   }

These are the codes i tried (sorry im not really great in coding) :

//if($_POST["length"] != -1)
   {
Trial 1 : //$query .= "TOP " . $_POST['start'] . " OFFSET " .                     $_POST['length'];


Trial 2 : //$query .= "SELECT * from item ORDER BY id DESC offset 0 rows fetch next 10 rows only ";


    Trial 3 ://$query .="AND id BETWEEN ".intval( $_POST["start"] )." AND ".intval( $_POST["length"] );" "

}

The result should be a pagination with 10 filtered records each.enter image description here

Update 1:

Here is the screenshot of the query i tried to test it in a MS SQL server but getting an error (using MS SQL 2008)

SQL Query

  • 写回答

2条回答 默认 最新

  • dongyuchen9276 2019-03-28 15:11
    关注

    Your approach depends on SQL Server version.

    Approach, based on ORDER BY clause with OFFSET and FETCH as a paging solution requires SQL Server 2012+. Your syntax seems correct, so next code should work:

    <?php
    if ($_POST["length"] != -1) {
        $query = "
            SELECT * 
            FROM item 
            ORDER BY id DESC OFFSET ".($_POST['start']-1)." ROWS FETCH NEXT ".$_POST["length"]." ROWS ONLY
        ";
    }
    ?>
    

    For SQL Server 2008+, you may use ROW_NUMBER() as a paging solution:

    <?php
    if ($_POST["length"] != -1) {
        $query = 
            "SELECT *
            FROM (
                SELECT 
                    *, 
                    ROW_NUMBER() OVER (ORDER BY id DESC) AS Rn
                FROM item
            )
            WHERE Rn BETWEEN ".$_POST['start']." AND ".($_POST['start'] + $_POST['length'] - 1);        
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度