Skip to content

Instantly share code, notes, and snippets.

@umarhussain88
Last active November 30, 2021 21:34
Show Gist options
  • Save umarhussain88/e9a2143ae2bd86a7628ca95e2029a149 to your computer and use it in GitHub Desktop.
Save umarhussain88/e9a2143ae2bd86a7628ca95e2029a149 to your computer and use it in GitHub Desktop.
from sqlalchemy import create_engine
import pandas as pd
params = urllib.parse.quote_plus(
r'Driver={ODBC Driver 17 for SQL Server};'
+ fr'Server={sql_server}'
+ fr',1433;Database={sql_db};'
+ fr'Uid={sql_user};Pwd={sql_password};'
+ r'Encrypt=yes;TrustServerCertificate=Yes;Connection Timeout=30;')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str, fast_executemany=True)
## pandas df#
df.to_sql('temp_tbl',schema='dbo',if_exists='replace',index=False,con=engine)
qry = """
SELECT a.ID
, b.Start_Date
, b.End_Date
, a.V1
, a.V2
, a.V3
FROM your_tbl a
LEFT JOIN test b
ON a.id = b.id
AND CAST(a.[Day] AS DATE) BETWEEN
CAST(b.[Start_Date] AS DATE)
AND CAST(b.[End_Date] AS DATE)
"""
output = pq.read_sql(qry,engine)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment