I'm trying to pass a an unknown number of params to SQL Server in python 3.6. Here is my code using pypyodbc:
cursor = cnxn.cursor()
theargs= ['1033286869','1053474957','1063654630','1104116235','1104910306','JASON']
thesql = """SELECT *
FROM BI_DUPLICATES_STAGE_0
WHERE DUP_ID IN (?, ?, ?, ?, ?)
AND FRST_NM = ?
"""
cursor.execute(thesql, theargs)
resultset = cursor.fetchall()
This works. However, I'm never sure how many DUP_IDs I'm going to have. I've seen some examples of using a list, but then if I have another variable such as is this case, FRST_NM
, then I can't just use the list.
So if somebody could provide a simple example of having a list (of varying length), and another variable and how to get SQL to run that I would greatly appreciate it! I'm not bound to using pypyodbc if that is the issue and there is another way to do this.
UPDATE:
Thank you for the nicely formatted answer. Just one quick follow-up question. I'm still a little unclear how I would format 2 lists if I had to produce something like:
SELECT * FROM BI_DUPLICATES_STAGE_0
WHERE DUP_ID IN (1033286869, 1053474957, 1063654630, 1104116235, 1104910306)
AND MID_NM IN ('SMITH','JON')
AND FRST_NM = 'JASON'
Without the nice format join, I have some mess like this:
SELECT * FROM BI_DUPLICATES_STAGE_0
WHERE DUP_ID IN (?,?,?,?,?)
AND MID_NM IN (?,?)
AND FRST_NM = ?
How would I format the list twice as suggested? Keeping in mind I won't know how long each list (the ID and MID_NM) are actually going to be.