1

I am working on pyodbc in Eclipse (4.3.2v20140221-1852) with PyDev on Win 7. My python is 3.2.5.

At my code:

 cursor.execute("select top " + str(1) + " a.my_id, a.mycode" + 
               "from my_table as a where a.mycode = ?", aGivenCode)

I got an error :

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Incorrect syntax near the keyword 'as'. (156) (SQLExecDirectW)")

Why I got error at " as a " ?

thanks !

2 Answers 2

2

A couple suggestions for future development:

  1. Use multi-line string notation """ to allow better identification of syntax errors (like the missing space between column and table in the original query).

  2. Instead of string concatenation, use a parameter for TOP values. The value must be wrapped in parentheses.

With these guidelines, your original code would be updated to:

top = 1
cursor.execute("""select top (?) a.my_id, a.mycode
                  from my_table as a
                  where a.mycode = ?""",
               (top, aGivenCode))
Sign up to request clarification or add additional context in comments.

Comments

1

Try this? I think you're missing a space in there:

cursor.execute("select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?", aGivenCode)

See how there is no space in between 'a.mycode' and 'from my_table'? I'm not 100% sure that is right, but give it a try.

These things are also easier to debug like this:

sql = "select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?"
print sql
cursor.execute(sql, aGivenCode)

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.