I'm trying to run an sql query that works as native sql code in a program like Azure, but throws programming errors when I try to use the exact code in python using SQLAlchemy with ODBC and pandas.
SQL code:
Select RecordNumbers -- ID des Falles
, Min(T.Created) As FirstRecord -- erste
From Data.Table1 V
Left Outer Join Data.Table2Version TV
On V.VersionNumber=TV.VersionNumber
Left Outer Join Data.Table3 T
On TV.IdT=T.IdT
And T.Type=11 -- nur Export
Where RType=1 -- nur was
And Doob1=1 -- nur was auch
And Doob2=1 -- nur anderes
Group By RecordNumber
This returns the two selected columns.
In SQLAlchemy, after establishing and testing a connection - dbConnection - I store query as text and use pandas to read the query:
from sqlalchemy import text
query = text("Select RecordNumbers, \
Min(T.Created) As FirstRecord -- erste \
From Data.Table1 V
\
Left Outer Join Data.Table2Version TV On V.VersionNumber=TV.VersionNumber \
Left Outer Join Data.Table3 T \
ON TV.IdT=T.IdT \
AND T.Type=11 -- nur Export \
Where (RType=1 -- nur was \
And Doob=1 -- nur was auch \
And Doob2=1 ) -- nur anderes \
Group By IdRecord \
Order By 1 Desc")
out = pd.read_sql_query(query, dBConnection)
This throws two errors for both variables in the select part of the query.
- ProgrammingError: (pyodbc.ProgrammingError) ('42S22', '[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name "FirstRecord".
- The multi-part identifier "T.CreatedAt" could not be bound.
Replacing the selected variables with "Select * From..." solves the problem, but the output is too large to be functional solution.
Trying to solve invalid column name, if I explicitly define the location of V.FirstRecord, it throws the same multi-part identifier error for this varible.
I've read about explicit and implicit queries, but think everything here is pretty explicit... maybe.
SQLAlchemy says: This error is a DBAPI Error and originates from the database driver (DBAPI), not SQLAlchemy itself.
I'm not very good at SQL, so would greatly appreciate being pointed in the right direction.
1条答案
按热度按时间lokaqttq1#
A string created like this:
does not actually contain any end of line characters. When printed, the output is
The inline comment effectively terminates parsing of the query.
As AlwaysLearning suggested, removing the comments will fix this. Another approach is to use triple-quoted strings which will create a multi-line string.