Python 2.7 MSSQL Incorrect Syntax near Order

Question:

I have searched high and low to look for the solution to this problem, I am receiving the error when I add the Order by to the statement:

(156, “Incorrect syntax near the keyword ‘Order’.DB-Lib error message 20018, severity 15:nGeneral SQL Server error: Check messages from the SQL Servern”)

The code in my .py file is:

db = pymssql.connect(server='DESKTOP-3G1FB9BSQLEXPRESS', user='sa', password='', database='Osmium')
cursor = db.cursor()
sql = "(SELECT TOP 1 * FROM delayed Order by ID ASC)"
cursor.execute(sql)

If I remove the ‘Order by ID ASC’ it executes fine, but I need to order the results and am unable to find a solution. Entering the query into SQL Server 2014 Management Studio and adding “Osmium.dbo.delayed” it returns the correct result, I just need it to work within the Python (2.7) script

SELECT TOP 1 * FROM Osmium.dbo.delayed Order by ID ASC
Asked By: George Crane

||

Answers:

Submitting this to make an answer, and explain why:

Change your sql variable declaration to be:

sql = "SELECT TOP 1 * FROM [delayed] ORDER BY [ID] ASC"

ORDER BY is a clause in T-SQL, and therefore doesn’t need parentheses to establish any order of operations. The square brackets can be used to surround certain objects in SQL Server to allow for use of reserved words (for example, if you have a column named something like [file]) or certain characters like a hyphen (a database named [your-db]).

Answered By: FlipperPA

It worked for me. when I granted the update permission.

Answered By: Kumar Ramanujam R