37

This is my sql

var maxLimit =100;
var sql = "Select Top @MaxLimit from Table WHere data =@Id"
conn.Query<Result>(sql, new  {
                Id = customerId,
                MaxLimit = maxLimit
            })

But I get a system error

incorrect syntax near @MaxLimit.

Is Dapper not able to parametrize fields like Top, or Fetch?

2 Answers 2

64

In SQL Server any top expression other than a numeric constant needs to be in parentheses.

SELECT TOP (@MaxLimit) FROM ...
1
  • 4
    Only supported in 2005 and greater. (showing my age)
    – mxmissile
    Apr 29, 2016 at 20:27
16

Newer versions of dapper have literal replacements and they work great in this case:

var sql = "Select Top {=MaxLimit} from Table WHere data = @Id";
1
  • I like this WAY better than the old version! thnx!
    – AcidRod75
    Dec 5, 2022 at 0:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.