You are here

public function DatabaseConnection_sqlsrv::addRangeToQuery in Drupal driver for SQL Server and SQL Azure 7.2

Same name and namespace in other branches
  1. 7.3 sqlsrv/database.inc \DatabaseConnection_sqlsrv::addRangeToQuery()
  2. 7 sqlsrv/database.inc \DatabaseConnection_sqlsrv::addRangeToQuery()

Internal function: add range options to a query.

This cannot be set protected because it is used in other parts of the database engine.

@status tested

1 call to DatabaseConnection_sqlsrv::addRangeToQuery()
DatabaseConnection_sqlsrv::queryRange in sqlsrv/database.inc
Override of DatabaseConnection::queryRange().

File

sqlsrv/database.inc, line 639
Database interface code for Microsoft SQL Server.

Class

DatabaseConnection_sqlsrv
Summary of DatabaseConnection_sqlsrv

Code

public function addRangeToQuery($query, $from, $count) {
  if ($from == 0) {

    // Easy case: just use a TOP query if we don't have to skip any rows.
    $query = preg_replace('/^\\s*SELECT(\\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(' . $count . ')', $query);
  }
  else {
    if ($this
      ->schema()
      ->EngineVersionNumber() >= 11) {

      // As of SQL Server 2012 there is an easy (and faster!) way to page results.
      $query = $query .= " OFFSET {$from} ROWS FETCH NEXT {$count} ROWS ONLY";
    }
    else {

      // More complex case: use a TOP query to retrieve $from + $count rows, and
      // filter out the first $from rows using a window function.
      $query = preg_replace('/^\\s*SELECT(\\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(' . ($from + $count) . ') ', $query);
      $query = '
          SELECT * FROM (
            SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.__line2) AS __line3 FROM (
              SELECT sub1.*, 1 AS __line2 FROM (' . $query . ') AS sub1
            ) as sub2
          ) AS sub3
          WHERE __line3 BETWEEN ' . ($from + 1) . ' AND ' . ($from + $count);
    }
  }
  return $query;
}