Reputation: 129
I have defined a parameter called CODE.
CODE is a list of strings, for instance 'Car', 'Bike', 'Boat' and so on.
I need to execute SQL queries that have the following pattern:
SELECT *
FROM Table
WHERE CODE = Car
or
SELECT *
FROM Table
WHERE CODE = Bike
and so on.
Is it possible to use the parameter directly in the query?
Like something like the following:
SELECT *
FROM Table
WHERE CODE = Parameter CODE?
Edit:
I'm using Python to make the query. Variable CODE comes from a column of a dataframe as follows:
import pandas as pd
import pyodbc
CODE=Table1['CODE']
dbconnection=pyodbc.connect('Driver={SQL Server};'
'Server=XXXX,1234;'
'Database=AAAA;'
'Trusted_Connection=yes;')
sql="SELECT * FROM DATABASE WHERE CODE = 'Bike'"
Selection=pd.read_sql(sql,dbconnection)
Upvotes: 0
Views: 577
Reputation: 616
You can use Python string formatting to replace the value. One type of formatting is the f-string syntax
#OLD (your approach)
sql="SELECT * FROM DATABASE WHERE CODE = 'Bike'"
#NEW - with formatting
sql=f"SELECT * FROM DATABASE WHERE CODE = '{CODE}'"
Upvotes: 0
Reputation: 511
If it isn't a long list of values in CODE, then you can do the following:
select * from Table where CODE IN ('Car', 'Bike', 'Boat', 'Motor', ...);
Upvotes: 1