Skip to content

Commit 23757b6

Browse files
committed
Add "OFFSET 0 ROWS" queries without an existing ordering or limit clause
Without this patch, subqueries with orderings result in an exception: ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified. (1033) (SQLExecDirectW)') Resolves issue #12.
1 parent b41e8b4 commit 23757b6

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

mssql/compiler.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,12 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
307307
params.extend(o_params)
308308
result.append('ORDER BY %s' % ', '.join(ordering))
309309

310+
# For subqueres with an ORDER BY clause, SQL Server also
311+
# requires a TOP or OFFSET clause which is not generated for
312+
# Django 2.x. See https://github.com/microsoft/mssql-django/issues/12
313+
if django.VERSION < (3, 0, 0) and not (do_offset or do_limit):
314+
result.append("OFFSET 0 ROWS")
315+
310316
# SQL Server requires the backend-specific emulation (2008 or earlier)
311317
# or an offset clause (2012 or newer) for offsetting
312318
if do_offset:

0 commit comments

Comments
 (0)