@@ -18,10 +18,14 @@ class SqlsrvDriver extends Nette\Object implements Nette\Database\ISupplementalD
1818 /** @var Nette\Database\Connection */
1919 private $ connection ;
2020
21+ /** @var string */
22+ private $ version ;
23+
2124
2225 public function __construct (Nette \Database \Connection $ connection , array $ options )
2326 {
2427 $ this ->connection = $ connection ;
28+ $ this ->version = $ connection ->getPdo ()->getAttribute (\PDO ::ATTR_SERVER_VERSION );
2529 }
2630
2731
@@ -88,15 +92,21 @@ public function formatLike($value, $pos)
8892 */
8993 public function applyLimit (& $ sql , $ limit , $ offset )
9094 {
91- if ($ limit >= 0 ) {
92- $ sql = preg_replace ('#^\s*(SELECT(\s+DISTINCT|\s+ALL)?|UPDATE|DELETE)#i ' , '$0 TOP ' . (int ) $ limit , $ sql , 1 , $ count );
93- if (!$ count ) {
94- throw new Nette \InvalidArgumentException ('SQL query must begin with SELECT, UPDATE or DELETE command. ' );
95+ if (version_compare ($ this ->version , 11 , '< ' )) { // 11 == SQL Server 2012
96+ if ($ limit >= 0 ) {
97+ $ sql = preg_replace ('#^\s*(SELECT(\s+DISTINCT|\s+ALL)?|UPDATE|DELETE)#i ' , '$0 TOP ' . (int ) $ limit , $ sql , 1 , $ count );
98+ if (!$ count ) {
99+ throw new Nette \InvalidArgumentException ('SQL query must begin with SELECT, UPDATE or DELETE command. ' );
100+ }
95101 }
96- }
97102
98- if ($ offset > 0 ) {
99- throw new Nette \NotSupportedException ('Offset is not supported by this database. ' );
103+ if ($ offset > 0 ) {
104+ throw new Nette \NotSupportedException ('Offset is not supported by this database. ' );
105+ }
106+ } elseif ($ limit >= 0 || $ offset > 0 ) {
107+ // requires ORDER BY, see https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx
108+ $ sql .= ' OFFSET ' . (int ) $ offset . ' ROWS '
109+ . 'FETCH NEXT ' . (int ) $ limit . ' ROWS ONLY ' ;
100110 }
101111 }
102112
0 commit comments