I have a SQL variable mem_dep When I am using it directly in variable sql then it is working absolutely fine. It is printing proper SQL statement but when I am passing another variable cat in variable sql with the value "mem_dep" then it is not working fine. It is just printing value of cat
mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
cob = "20223456"
cat = "mem_dep"
Below code is working absolutely fine
def calc():
sql = mem_dep.format(Business_date = cob)
print(sql)
Output:
calc() # calling function
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql
But below code is not working if I am passing variable cat in a function with the same value as variable name mem_dep
def calc(cat):
sql = cat.format(Business_date = cob)
print(sql)
Output:
calc(cat) # calling function
mem_dep #printing sql
How can I pass SQL variable as a variable in the function in this case?
I tried below code also but not working
def calc(cat):
tmp_sql = "{}".format(cat)
sql = tmp_sql.format(Business_date = cob)
print(sql)
Output:
calc(cat) # calling function
mem_dep #printing sql
Expected output:
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql
>Solution :
From what I understand cat has the name of the SQL variable which contains your SQL string. And you want to access the SQL string from cat without knowing the value of cat. You can use getattr for this purpose and wrap everything in a class like below:
class SQLCalc:
def __init__(self):
self.mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
self.cob = "20223456"
self.cat = "mem_dep"
def calc(self):
sql = getattr(self, self.cat).format(Business_date = self.cob)
print(sql)
sql_calc = SQLCalc()
sql_calc.calc()