35

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Justin Homes
  • 3,739
  • 9
  • 49
  • 78

2 Answers2

62

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

SELECT TOP (@MaxLimit) FROM ...
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
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";
Lars
  • 1,699
  • 2
  • 22
  • 32