framework/db/schema/mssql/CMssqlCommandBuilder.php
public function applyLimit($sql, $limit, $offset)
	{
		$limit = $limit!==null ? (int)$limit : -1;
		$offset = $offset!==null ? (int)$offset : -1;
		if ($limit > 0 && $offset <= 0) //just limit
			$sql = preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',"\\1SELECT\\2 TOP $limit", $sql);
		elseif($limit > 0 && $offset > 0)
			$sql = $this->rewriteLimitOffsetSql($sql, $limit,$offset);
		return $sql;
	}
public function applyLimit($sql, $limit, $offset)
	{
		$limit = $limit!==null ? (int)$limit : -1;
		$offset = $offset!==null ? (int)$offset : -1;
		if ($limit > 0 && $offset <= 0) //just limit
			$sql = preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',"\\1SELECT\\2 TOP $limit", $sql);
		elseif($limit > 0 && $offset > 0)
			$sql = $this->rewriteLimitOffsetSql($sql, $limit,$offset);
		return $sql;
	}
public function applyLimit ( $ sql , $ limit , $ offset ) { $ limit = $ limit !== null ? ( int ) $ limit : - 1 ; $ offset = $ offset !== null ? ( int ) $ offset : - 1 ; if ( $ limit > 0 && $ offset <= 0 ) //just limit $ sql = preg_replace ( '/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i' , "\\1SELECT\\2 TOP $limit" , $ sql ) ; elseif ( $ limit > 0 && $ offset > 0 ) $ sql = $ this -> rewriteLimitOffsetSql ( $ sql , $ limit , $ offset ) ; return $ sql ; }
This is a port from Prado Framework.

Overrides parent implementation. Alters the sql to apply $limit and $offset.
The idea for limit with offset is done by modifying the sql on the fly
with numerous assumptions on the structure of the sql string.
The modification is done with reference to the notes from
http://troels.arvin.dk/db/rdbms/#select-limit-offset

<code>
SELECT * FROM (
SELECT TOP n * FROM (
SELECT TOP z columns      -- (z=n+skip)
FROM tablename
ORDER BY key ASC
) AS FOO ORDER BY key DESC -- ('FOO' may be anything)
) AS BAR ORDER BY key ASC    -- ('BAR' may be anything)
</code>

<b>Regular expressions are used to alter the SQL query. The resulting SQL query
may be malformed for complex queries.</b> The following restrictions apply

<ul>
<li>
In particular, <b>commas</b> should <b>NOT</b>
be used as part of the ordering expression or identifier. Commas must only be
used for separating the ordering clauses.
</li>
<li>
In the ORDER BY clause, the column name should NOT be be qualified
with a table name or view name. Alias the column names or use column index.
</li>
<li>
No clauses should follow the ORDER BY clause, e.g. no COMPUTE or FOR clauses.
</li>
</ul>

@param string $sql SQL query string.
@param integer $limit maximum number of rows, -1 to ignore limit.
@param integer $offset row offset, -1 to ignore offset.
@return string SQL with limit and offset.

@author Wei Zhuo <weizhuo[at]gmail[dot]com>
This is a port from Prado Framework .