Skip to content
Advertisement

Pass Column Names into SQL statement in dynamic way – Python- SQL Server

query = ('SELECT ? from table', fields)

Example of ‘fields’ value = name, surname, date

I can put ‘fields’ in a list but I do not know how many (?) to put inside the query. Because, fields variable will include sometimes 5, sometimes 10 column names. I am trying to pass column names dynamically to the query.

How can I solve this problem?

Advertisement

Answer

A statement could be formed like so. Values will be like “(?, ?, ?, ?)” depending on the length of fields.

# create a comma separated list of question marks
# then surround with parenthesis  
values = '('+', '.join(['?']*len(fields))+')'
        
query=('SELECT '+values+' from table',fields) 

Not saying that this will work since you didn’t share specifics of how you are connecting to or querying SQL Server.

Instead you could use the join str method:

table_name = 'MyTable'

fields = ['col1','col2','col3']

values = ', '.join(fields)
        
statement = 'SELECT '+values+' from '+table_name

query
'SELECT col1, col2, col3 from MyTable'

query=(statement)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement