0

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)
2
  • are you using Python to make the query or is this all in SQL? Commented Nov 4, 2022 at 13:34
  • 1
    Im using Python. I edited the post. Commented Nov 4, 2022 at 14:03

2 Answers 2

1

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', ...);
Sign up to request clarification or add additional context in comments.

Comments

0

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}'"

2 Comments

You should use a parametrized query, not string formatting.
@Barmar you are 100% correct. Thanks for the update

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.