Commit 80b18c7f authored by Bill Schaller's avatar Bill Schaller

Fix DISTINCT queries with limit and no order on SQL Server 2012

parent 8e65cdc7
...@@ -120,10 +120,18 @@ class SQLServer2012Platform extends SQLServer2008Platform ...@@ -120,10 +120,18 @@ class SQLServer2012Platform extends SQLServer2008Platform
if ($orderByPos === false if ($orderByPos === false
|| substr_count($query, "(", $orderByPos) - substr_count($query, ")", $orderByPos) || substr_count($query, "(", $orderByPos) - substr_count($query, ")", $orderByPos)
) { ) {
if (strtoupper(substr($query, 0, 15)) == 'SELECT DISTINCT') {
// SQL Server won't let us order by a non-selected column in a DISTINCT query,
// so we have to do this madness. This says, select 0 as column one, and order
// by column one.
$query = 'SELECT DISTINCT 0,' . substr($query, 15);
$query .= " ORDER BY 1";
} else {
// In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you use constant expressions in // In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you use constant expressions in
// the order by list. // the order by list.
$query .= " ORDER BY (SELECT 0)"; $query .= " ORDER BY (SELECT 0)";
} }
}
if ($offset === null) { if ($offset === null) {
$offset = 0; $offset = 0;
......
...@@ -247,7 +247,7 @@ class SQLServer2012PlatformTest extends AbstractSQLServerPlatformTestCase ...@@ -247,7 +247,7 @@ class SQLServer2012PlatformTest extends AbstractSQLServerPlatformTestCase
{ {
$sql = $this->_platform->modifyLimitQuery("SELECT DISTINCT id_0 FROM (SELECT k0_.id AS id_0 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result", 10); $sql = $this->_platform->modifyLimitQuery("SELECT DISTINCT id_0 FROM (SELECT k0_.id AS id_0 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result", 10);
$expected = "SELECT DISTINCT id_0 FROM (SELECT k0_.id AS id_0 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY"; $expected = "SELECT DISTINCT 0, id_0 FROM (SELECT k0_.id AS id_0 FROM key_measure k0_ WHERE (k0_.id_zone in(2))) dctrn_result ORDER BY 1 OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY";
$this->assertEquals($sql, $expected); $this->assertEquals($sql, $expected);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment