I have a SQL query which I want to iterate using python for loop. Is there a way where I can define a variable inside the sql query and update it’s value with each python loop?
date1 = datetime.date(2017, 1, 1) date2 = datetime.date(2017, 12, 31) for d in daterange(date1, date2): SQL = "SELECT * FROM table WHERE TABLE.CREATED_AT = '2017-01-01' cursor.execute(sql)
I want to iterate through all the dates of year 2017(created_at). This is a sample problem, I can’t use WHERE claus for date in my query as it is a complex query with lot of dependencies. Can some one help me regarding this? I apologise in advance if there is any error as I am new to this platform and new to using sql using python.
Advertisement
Answer
For the date in the format you indicated I would say that you should proceed in this way:
import datetime date1 = datetime.date(2017, 1, 1) date2 = datetime.date(2017, 12, 31) date_generated = [date1 + datetime.timedelta(days=x) for x in range(0, (date2-date1).days)] for date in date_generated: SQL = "SELECT * FROM table WHERE TABLE.CREATED_AT = '{}';".format(date) cursor.execute(sql)