1

So I'm trying to use the following syntax to produce a row number for each result, where:

  • @row is created as the query runs and
  • @search is a parameter I've added myself:
var cmd = new MySqlCommand();
cmd.CommandText = @"SET @row = 0;
                    SELECT
                        (@row:= @row + 1) AS row,
                            *
                    FROM
                        clients
                    WHERE
                        name CONCAT('%', @search, '%')";

cmd.Parameters.AddWithValue("@search", "whatever");

try
{
    cmd.Connection.Open();
    using (var reader = cmd.ExecuteReader())
    {
        // blah blah
    }
}
catch (Exception ex)
{
    cmd.Connection.Close();

}  

This query works fine if I run the MySQL straight in the database, but I get an error from the c#:

Parameter @row must be defined

..if I use a MySqlCommand object.

Is there a way around this problem?

Thanks

Dave
  • 5,283
  • 7
  • 44
  • 66
  • It seems as though MySqlCommand may be attempting to parse and bind `@row` (as it is doing for `@search`).. – user2864740 Jan 25 '20 at 21:51
  • @user2864740 yes that's correct - but how do I tell the object to IGNORE that variable? – Dave Jan 25 '20 at 21:52
  • I found "Note. *Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL.* To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL." (link dead) - so, if such snipped is honest, I would expect code to use `?var` instead of `@var` *for a 'modern' provider* without 'old syntax' enabled. – user2864740 Jan 25 '20 at 21:54
  • Unfortunately.. not so honest: https://dev.mysql.com/doc/dev/connector-net/8.0/html/P_MySql_Data_MySqlClient_MySqlCommand_Parameters.htm (perhaps there is a bug report?) – user2864740 Jan 25 '20 at 21:57
  • Ahh, see the connection string [AllowUserVariables] options: https://mysqlconnector.net/connection-options/ .. that's not confusing at all. – user2864740 Jan 25 '20 at 22:00

0 Answers0