Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 MSSQL Incorrect Syntax near Order

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 Server\n")

The code in my .py file is:

db = pymssql.connect(server='DESKTOP-3G1FB9B\SQLEXPRESS', 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
like image 765
George Crane Avatar asked Jun 29 '26 11:06

George Crane


1 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]).

like image 193
FlipperPA Avatar answered Jul 01 '26 00:07

FlipperPA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!