Reputation: 379
I've begun using python to pull queries from Teradata using PyTd. Coming from SAS, I'd like to know if there is a way to pass parameters/variables similar to SAS Macro Variables. Our company has different databases for each state where I run the same query but need to update the state each time. The example below I'd like to substitute {macroVariable} for each state, looping through and running a new query, then I would mend all the queries. I've found some examples of using a for loop, but couldn't quite get it to work the way I needed.
import teradata as td
import pandas as pd
from teradata import tdodbc
udaExec = td.UdaExec(appConfigFile="udaexec.ini")
with udaExec.connect("${dataSourceName}") as session:
query1 = """{macroVariable}_db_1;"""
query2 = """select * from table"""
session.execute(query1)
session.execute(query2)
df = pd.read_sql(query2, session)
Upvotes: 1
Views: 506
Reputation: 180
I haven't used PYTD, but I use sql alchemy and this type of coding works for me. Let me show you with an example.
import sqlalchemy as sa
import pandas as pd
td_engine = '%s://%s:%s@%s/%s'%(td_driver, username, password, td_host,dbname)
td_conn = sa.create_engine(td_engine)
x = '202012' # your variable (similar to SAS macro variable) that you define outside of teradata envrionment
td_sql = ''' select top 10* from customer_{}'''.format(x)
df = pd.read_sql(td_sql, td_conn)
Upvotes: 1