Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Issue with handling '?' character in SQL strings when using SQL Server

Open eatmeatHJ opened this issue 2 years ago • 1 comments

I've encountered an issue when using Dapper with SQL Server. In my SQL queries, I sometimes include '?' characters inside the string values, as a part of the string itself, not as a parameter placeholder. For example, a query might look like this:

string sql = @"INSERT INTO test_table2 ([name0],[name1],[name2]) VALUES ('?a?', '3.?a?', @name)";
var dp = new Dapper.DynamicParameters();
dp.Add("name", "qq");
conn.Execute(sql, dp);

In this example, '?a?' and '3.?a?' are string values to be inserted into the table, and @name is the only actual parameter in the query.

However, when I execute such a query with Dapper, it throws an exception with the message: "When passing parameters by position, each parameter can only be referenced once."

Is there any way to configure Dapper to correctly handle the '?' characters in SQL strings when using SQL Server?

Any help would be greatly appreciated.

eatmeatHJ avatar Jun 11 '23 12:06 eatmeatHJ

That is an unfortunate false positive. Sorry, right now that isn't configurable. The only immediate fix I have for you is to break the literal in your SQL, for example '?' + 'a?', '3.?' + 'a?', which most SQL implementations will recombine trivially (so no real overhead, other than ugliness)

Definitely something for us to consider for the future.

mgravell avatar Jun 11 '23 22:06 mgravell