Skip to content

Commit

Permalink
Fixes yiisoft#4299
Browse files Browse the repository at this point in the history
  • Loading branch information
qiangxue committed Jul 14, 2014
1 parent 4fdfe7a commit 0a5894f
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions framework/db/mssql/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,21 +135,14 @@ public function build($query, $params = [])

$params = empty($params) ? $query->params : array_merge($params, $query->params);

if (empty($query->orderBy) && ($this->hasLimit($query->limit) || $this->hasOffset($query->offset)) && $this->isOldMssql()) {
// hack so LIMIT will work because ROW_NUMBER requires an ORDER BY clause
$orderBy = 'ORDER BY (SELECT NULL)';
} else {
$orderBy = $this->buildOrderBy($query->orderBy);
}

$clauses = [
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildJoin($query->join, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildHaving($query->having, $params),
$orderBy,
$this->buildOrderBy($query->orderBy),
$this->isOldMssql() ? '' : $this->buildLimit($query->limit, $query->offset),
];

Expand Down Expand Up @@ -209,6 +202,12 @@ private function rewriteLimitOffsetSql($sql, $limit, $offset, $query)
}
}
$sql = str_replace($originalOrdering, '', $sql);

if ($originalOrdering === '') {
// hack so LIMIT will work because ROW_NUMBER requires an ORDER BY clause
$originalOrdering = 'ORDER BY (SELECT NULL)';
}

$sql = preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 rowNum = ROW_NUMBER() over ({$originalOrdering}),", $sql);
$sql = "SELECT TOP {$limit} {$select} FROM ($sql) sub WHERE rowNum > {$offset}";
return $sql;
Expand Down

0 comments on commit 0a5894f

Please sign in to comment.