From 23757b63d687b6b682d5734e2a338a96fe949719 Mon Sep 17 00:00:00 2001 From: randlet Date: Fri, 26 Mar 2021 12:38:40 -0400 Subject: [PATCH] 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. --- mssql/compiler.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mssql/compiler.py b/mssql/compiler.py index 28d1fbd2..9df8081e 100644 --- a/mssql/compiler.py +++ b/mssql/compiler.py @@ -307,6 +307,12 @@ def as_sql(self, with_limits=True, with_col_aliases=False): params.extend(o_params) result.append('ORDER BY %s' % ', '.join(ordering)) + # For subqueres with an ORDER BY clause, SQL Server also + # requires a TOP or OFFSET clause which is not generated for + # Django 2.x. See https://github.com/microsoft/mssql-django/issues/12 + if django.VERSION < (3, 0, 0) and not (do_offset or do_limit): + result.append("OFFSET 0 ROWS") + # SQL Server requires the backend-specific emulation (2008 or earlier) # or an offset clause (2012 or newer) for offsetting if do_offset: