如何在 sql 服务器中使用 TOP

How to use TOP in sql server

我的代码如下:

public function findAllByPagePlain($limit, $offset, $q, $category_id, $column, $order)
    {
        $query = "SELECT DISTINCT TOP $limit p.* FROM ec_product p ";
        $keywordQuery = "(p.name REGEXP '$q' OR p.status REGEXP '$q' OR p.description REGEXP '$q') ";
        if ($category_id != -1) {
            $query = $query . ", product_category pc WHERE pc.product_id=p.id AND pc.category_id=$category_id ";
            if ($q != "") $query = $query . "AND " . $keywordQuery;
        } else {
            if ($q != "") $query = $query . "WHERE " . $keywordQuery;
        }
        $query = $query . "ORDER BY p." . $column . " " . $order . " OFFSET $offset ";
        return $this->db->get_list($query);
    }

我正在尝试使用 TOP 从我的数据库中获取第一个 n rows。但它一直给我一个错误说

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '0'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '0'. ) )

有人知道如何解决这个问题吗?

考虑以下因素:

  • 你的 Incorrect syntax near '0' 错误的原因是你没有为 OFFSET ... FETCH 子句使用正确的语法。我认为,您正在尝试实施分页解决方案,因此请使用 OFFSET ... FETCH 子句而不是 TOP 子句。
  • REGEXP 语法是 MySQL 的一部分,对于 MS SQL 服务器,您应该使用 LIKEPATINDEX()
  • 作为重要说明,重写您的代码并使用参数化语句来防止 SQL 注入攻击(如评论中所述)。

像下面的例子一样更改函数以解决 Incorrect syntax near '0' 错误:

<?php
public function findAllByPagePlain($limit, $offset, $q, $category_id, $column, $order)
    {
        $query = "SELECT DISTINCT p.* FROM ec_product p ";
        $keywordQuery = "(p.name LIKE '%$q%' OR p.status LIKE '%$q%' OR p.description LIKE '%$q%') ";
        if ($category_id != -1) {
            $query = $query . ", product_category pc WHERE pc.product_id=p.id AND pc.category_id=$category_id ";
            if ($q != "") $query = $query . "AND " . $keywordQuery;
        } else {
            if ($q != "") $query = $query . "WHERE " . $keywordQuery;
        }
        $query = $query . "ORDER BY p." . $column . " " . $order . " OFFSET ". $offset . " ROWS FETCH NEXT " . $limit. " ROWS ONLY";
        return $this->db->get_list($query);
    }
?>