0

I'm searching an SQL table for customers who's name starts with my input and i have problem writing the "Starting With" logic, it works fine when its WHERE ? =. i'm using pyodbc and using driver ODBC Driver 17 for SQL Server

i've seen alot of answers on similar problems but they always refer to using the code %s, and that does not work when i try it

I've tried many different ways of writing LIKE '%' but i cannot find any examples of this

my current code is:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName = ?", Company, CustomerName)
    result = cursor.fetchall()
    for row in result:
      print (row)

CustomerName var set to "Mic" and the the result should be:

Microsoft

Micro systems

etc..

Thanks you

2
  • which database are you pulling data from? CONCAT might not be available, you might have to do a '%'+searchstring+%' Commented Feb 6, 2019 at 10:11
  • Hi, Microsoft SQL Server Commented Feb 6, 2019 at 10:23

1 Answer 1

3

You need to concatenate the parameter with the % wildcard. In MySQL you use the CONCAT() function, in SQL-Server you use the + operator.

Also, the parameters that fill in the placeholders should be in a tuple, not separate arguments to cursor.execute().

MySQL:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName LIKE CONCAT(?, '%')", (Company, CustomerName))

SQL-Server:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName ? + '%'", (Company, CustomerName))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.