I would like to transfer most of my code written on T-SQL to Python, and came across basic data problems that could not be solved by searching in the SQLAlchemy documentation and in other forums.
Question:
How can I implement the following query options with SQLAlchemy (example for the test - below)?
select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner server2.database1.schema1.table_b as b on a.fileld1 = b.fileld1
select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner dataset_variable (**) as b on a.fileld1 = b.fileld1
The result of the query - print (select) (see below in the test case) returns an error: sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42S02', "[42S02] [M icrosoft] [ODBC SQL Server Driver] [SQL Server] Invalid object name 'server2.database1schema1.table_b'.
** Data received from another SQLAlchemy session (server2.database1.schema1.table_b) and stored in the variable dataset_variable
Test connection example: Two linked sql servers are used.
engine = create_engine("mssql+pyodbc://@{server1}/{}?driver=SQL+Server?trusted_connection=yes", echo=True)
metadata = MetaData(engine)
Base = declarative_base(metadata=metadata)
class table_a(Base):
__tablename__ = 'table_a '
__table_args__ = {
'schema': 'database1.schema1'
}
id = Column(Integer, primary_key=True)
f1 = Column(String(100))
f2 = Column(String(100))
class table_b(Base):
__tablename__ = 'table_b '
__table_args__ = {
'schema': 'server2.database1.schema1'
}
id = Column(Integer, primary_key=True)
f1 = Column(String(100))
f2 = Column(String(100))
Session = sessionmaker(bind=engine)
session = Session()
select = session.query(table_b.id).first()
print(select)