Index: Doctrine/Connection/Mssql.php =================================================================== --- Doctrine/Connection/Mssql.php (revision 6859) +++ Doctrine/Connection/Mssql.php (working copy) @@ -164,11 +164,11 @@ $helper_string = stristr($query, $orders[$i]); $from_clause_pos = strpos($helper_string, ' FROM '); - $fields_string = substr($helper_string, 0, $from_clause_pos + 1); + $fieldsString = substr($helper_string, 0, $from_clause_pos + 1); - $field_array = explode(',', $fields_string); - $field_array = array_shift($field_array); - $aux2 = spliti(' as ', $field_array); + $fieldArray = explode(',', $fieldsString); + $fieldArray = array_shift($fieldArray); + $aux2 = spliti(' as ', $fieldArray); $aux2 = explode('.', end($aux2)); $aliases[$i] = trim(end($aux2)); @@ -184,13 +184,27 @@ $selectReplace .= 'DISTINCT '; } - $fields_string = substr($query, strlen($selectReplace), strpos($query, ' FROM ') - strlen($selectReplace)); - $field_array = explode(',', $fields_string); - $aux2 = explode('.', $field_array[0]); - $key_field = trim(end($aux2)); + $fieldsString = substr($query, strlen($selectReplace), strpos($query, ' FROM ') - strlen($selectReplace)); + $fieldArray = explode(',', $fieldsString); + + // check if first field is in form "x as y" + if (stripos($fieldArray[0], 'as') !== false) + { + // detect split string: as or AS + $split = strpos($fieldArray[0], 'as') !== false ? 'as' : 'AS'; + + // split into array('x', 'y') + $aux2 = explode($split, $fieldArray[0]); + } else { + // field must be in form "x.y" + // split into array('x', 'y') + $aux2 = explode('.', $fieldArray[0]); + } + + $keyField = trim(end($aux2)); $query = preg_replace('/^'.$selectRegExp.'/i', $selectReplace . 'TOP ' . ($count + $offset) . ' ', $query); - $query = 'SELECT TOP ' . $count . ' ' . $this->quoteIdentifier('inner_tbl') . '.' . $key_field . ' FROM (' . $query . ') AS ' . $this->quoteIdentifier('inner_tbl'); + $query = 'SELECT TOP ' . $count . ' ' . $this->quoteIdentifier('inner_tbl') . '.' . $keyField . ' FROM (' . $query . ') AS ' . $this->quoteIdentifier('inner_tbl'); if ($orderby !== false) { $query .= ' ORDER BY ';