I'm able to connect and do a basic query off a SQL Server database via Python but once I start adding INNER JOINs and such to the query Python errors out with:
Incorrect syntax near the keyword 'Order'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n
I'll put the code below but I am thinking there must be some Python formatting I am getting wrong because the query works using other SQL tools.
In my searches I see that INNER JOIN should have the ON portion indented when using T-SQL in Python. Since I have so many INNER JOINs, maybe I am indenting incorrectly? I also saw that when you break up SQL in Python you have to put a \ at the end of each line.
Any help or links are appreciated!
import pymssql
conn = pymssql.connect(server= 'xxx',
user= 'xxx',
password= 'xxx',
database= 'xxx'
)
cursor = conn.cursor()
sql = "SELECT PatientInfo.MRN, AccountPersonalInfo.LastName, Visit.VisitNumber, PatientInfo.FirstName, PatientInfo.LastName, AccountPersonalInfo.FirstName, Report.LastSignDate, Order.ProcedureDescList, Visit.Facility, Order.CompleteDate, Order.FillerOrderNumber \
FROM ((Comm4.dbo.Order Order INNER JOIN Comm4.dbo.Report Report \
ON Order.ReportID=Report.ReportID) \
INNER JOIN (Comm4.dbo.PatientInfo PatientInfo INNER JOIN Comm4.dbo.Visit Visit \
ON PatientInfo.PatientID=Visit.PatientID) \
ON Order.VisitID=Visit.VisitID) INNER JOIN Comm4.dbo.AccountPersonalInfo AccountPersonalInfo \
ON Report.SignerAcctID=AccountPersonalInfo.AccountID \
WHERE PatientInfo.MRN<>'TEMPORARY' AND Report.LastSignDate>={ts '2020-09-01 00:00:00'} AND Report.LastSignDate<{ts '2020-10-01 00:00:00'}) \
ORDER BY Report.LastSignDate, PatientInfo.MRN"
cursor.execute(sql)
row = cursor.fetchone()
conn.close()
print(row)