Search code examples
sqlparameterssqlalchemylimitexecute

sqlalchemy execute sql with TOP parametrized


I want to use limit in mssql, which is TOP, parametrized. I hoped I can get top parametrized like that:

engine.execute( text("select top :t * from Orders), t=100)  

but I get: Statement(s) could not be prepared. (8180) (SQLExecDirectW)') 'select top ? * from Orders' (100,)

With top fixed or out it works fine.

Any ideas?


Solution

  • As indicated in this answer, assuming you are using at least SQL Server 2005, you should be able to run:

    engine.execute(text('select top (:t) * from Orders'), t=100)
    

    SQL Server should accept the parameter as long as it's enclosed in parentheses.