diff --git a/pegjs/transactsql.pegjs b/pegjs/transactsql.pegjs index 21317628..d321c9ee 100644 --- a/pegjs/transactsql.pegjs +++ b/pegjs/transactsql.pegjs @@ -1345,8 +1345,8 @@ cte_column_definition select_stmt_nake = __ cte:with_clause? __ KW_SELECT ___ opts:option_clause? __ - top: top_clause? __ d:KW_DISTINCT? __ + top: top_clause? __ c:column_clause __ f:from_clause? __ w:where_clause? __ diff --git a/src/select.js b/src/select.js index 287214d4..b65a004e 100644 --- a/src/select.js +++ b/src/select.js @@ -76,9 +76,8 @@ function selectToSQL(stmt) { where, } = stmt const clauses = [withToSQL(withInfo), 'SELECT', toUpper(asStructVal)] - clauses.push(topToSQL(top)) if (Array.isArray(options)) clauses.push(options.join(' ')) - clauses.push(distinctToSQL(distinct), columnsToSQL(columns, from)) + clauses.push(distinctToSQL(distinct), topToSQL(top), columnsToSQL(columns, from)) const { position } = into let intoSQL = '' if (position) intoSQL = commonOptionConnector('INTO', selectIntoToSQL, into) diff --git a/test/transactsql.spec.js b/test/transactsql.spec.js index 44ac3e87..198b30cf 100644 --- a/test/transactsql.spec.js +++ b/test/transactsql.spec.js @@ -12,8 +12,10 @@ describe('transactsql', () => { } it('should support select top n', () => { - const sql = 'select top 3 * from tableA' + let sql = 'select top 3 * from tableA' expect(getParsedSql(sql)).to.equal('SELECT TOP 3 * FROM [tableA]') + sql = `SELECT DISTINCT TOP 2 FirstName, LastName FROM Students WHERE GraduationYear = 2003 ORDER BY GradePointAverage DESC;` + expect(getParsedSql(sql)).to.equal('SELECT DISTINCT TOP 2 [FirstName], [LastName] FROM [Students] WHERE [GraduationYear] = 2003 ORDER BY [GradePointAverage] DESC') }) it('should support select top n percent', () => {