ZF 1 doesn't implement pagination on SQL Server correctly although ZF 2 does.
I've solved the problem by subclassing Zend_Db_Adapter_Pdo_Mssql
:
class My_Zend_Db_Adapter_Pdo_Mssql extends Zend_Db_Adapter_Pdo_Mssql
{
/**
* @see Zend_Db_Adapter_Pdo_Mssql::limit()
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/** @see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('count parameter invalid: ' . $count);
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('offset parameter invalid: ' . $count);
}
if (0 == $offset) {
$sql = preg_replace('/^SELECT\s+(DISTINCT\s)?/i', 'SELECT $1TOP ' . ($count+$offset) . ' ', $sql);
return $sql;
}
$selectStart = stripos($sql, 'SELECT');
$fromStart = stripos($sql, 'FROM');
$orderby = stristr($sql, 'ORDER BY');
if ($orderby === false) {
$orderby = 'ORDER BY (SELECT 1)';
}
$sql = rtrim(str_replace($orderby, '', $sql));
$selectParams = trim(substr($sql, $selectStart + 6, $fromStart - $selectStart - 6));
$selectParams .= ', ROW_NUMBER() OVER (' . $orderby . ') AS [ZEND_ROW_NUMBER]';
$sql = substr($sql, 0, $selectStart + 6) . ' ' . $selectParams . ' ' . substr($sql, $fromStart);
$outerSql = 'SELECT * FROM (' . $sql . ') AS [ZEND_OFFSET_EMULATION]'
. ' WHERE [ZEND_OFFSET_EMULATION].[ZEND_ROW_NUMBER] BETWEEN '
. ($offset + 1) . ' AND '
. ($offset + $count)
. ' ORDER BY [ZEND_ROW_NUMBER] ASC';
return $outerSql;
}
}