0

When I run below code which incorporates TOP ? in a select statement and I am unable to resolve.

Code:

cnt = self.getCount()
#cnt = 2
query = "select distinct top ? id, indicator from [TABLE] ORDER BY id ASC"
connsql = self.sql_connection()
resultset = connsql.cursor().execute(query, cnt).fetchall()
connsql.cursor().commit()
connsql.close()

I get this syntax error:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '@P1'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2961127
  • 963
  • 2
  • 17
  • 29
  • 2
    SQL Server does accept [a variable as the `TOP` quantity](https://learn.microsoft.com/en-us/sql/t-sql/queries/top-transact-sql?view=sql-server-ver15), so you should be able to pass it as an argument. Maybe this will help: https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python – Alex Dec 18 '19 at 20:28
  • You just need to wrap your ? with parenthesis. distinct top (?) – Sean Lange Dec 18 '19 at 20:43
  • @Alex Thank you.Got it. – user2961127 Dec 18 '19 at 20:57

0 Answers0