|
发表于 2012-11-27 16:10:26
|
显示全部楼层
本帖最后由 CurveSoft 于 2012-11-27 16:11 编辑
又修改了一下,楼主原来代码中
这段似乎本意是$sql中原来有ORDER BY的话就移除,因为MSSQL 2005不允许子查询中有ORDER BY,但是如果$sql里面原来没有ORDER BY子句的话,这样做整个SQL就会被清空了
于是我改了一下,如下:
PHP复制代码
function _limit ($sql, $limit, $offset) {
// $i = $limit + $offset;
// return preg_replace ( '/(^\SELECT (DISTINCT)?)/i', '\\1 TOP ' . $i . ' ', $sql );
if (! $offset) {
return preg_replace ( '/(^\SELECT (DISTINCT)?)/i', '\\1 TOP ' . $limit . ' ', $sql );
}
// As of SQL Server 2012 (11.0.*) OFFSET is supported
if (version_compare ( $this->version (), '11', '>=' )) {
return $sql . ' OFFSET ' . ( int ) $offset . ' ROWS FETCH NEXT ' . ( int ) $limit . ' ROWS ONLY';
}
// As of SQL Server 2005 (9.0.*) ROW_NUMBER is supported
if (version_compare ( $this->version (), '9', '>=' )) {
$orderby = 'ORDER BY ' . (empty ( $this->ar_orderby ) ? 'getdate()' : implode ( ', ', $this->ar_orderby ));
$p = strrpos ( $sql, 'order by' );
if ($p) {
$sql = empty ( $this->ar_orderby ) ? $sql : trim ( substr ( $sql, 0, $p ) );
}
return 'SELECT ' . (count ( $this->ar_select ) === 0 ? '*' : implode ( ', ', $this->ar_select )) . " FROM (\n" . preg_replace ( '/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER(' . $orderby . ') AS ' . $this->_escape_identifiers ( 'CI_rownum' ) . ', ', $sql ) . "\n) AS " . $this->_escape_identifiers ( 'CI_subquery' ) . "\nWHERE " . $this->_escape_identifiers ( 'CI_rownum' ) . ' BETWEEN ' . (( int ) $offset + 1) . ' AND ' . ($offset + $limit);
}
// TODO: Lower than 9.0 version (SQL Server 2000) need you to write
return $sql;
}
复制代码
不知道这样对不对,至少在我的应用里面不会有问题,因为我的查询SQL里面不会在第一步SQL里写ORDER BY的。
|
|