是否可以在MySqlCommand中使用MySql赋值运算符(:=)?

时间:2019-05-21 20:17:20

标签: c# mysql .net parameters mysql-connector

我有一个在MySql工作台中运行良好的查询,但是通过MySqlCommand.ExecuteReader运行时会产生语法错误"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= 0+1 AS Rank, z.* 
FROM(SELECT MemberId, Valu' at line 2"。所讨论的语法是select(即SELECT @r := @r + 1)内部的变量赋值。如果相关,我正在使用.net连接器v.6.9.9。另外,这是我的连接字符串:"server=mymysqlserveraddress;port=3306;database=dbName;user id=username;password=********;Convert Zero Datetime=True;Allow User Variables=true"

我尝试在连接字符串中设置Allow User Variables = true,如下所示:Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand?

我寻找了与此匹配的其他问题,但最终,我只发现了一个相同的问题,只是在Java中处于休眠状态:How can I use MySQL assign operator(:=) in hibernate native query?

这是在MySql Workbench中工作的原始sql查询:

SELECT Rank, Value 
FROM (SELECT @r := @r+1 AS Rank, z.* 
      FROM(SELECT MemberId, Value 
           FROM (SELECT Id, MemberId, Value, CreatedDate, EventId 
                 FROM Scores
                 WHERE (LoadTime IS NULL AND EventId = 408)
                 ORDER BY Value DESC
                ) AS sub 
     )z, 
     (SELECT @r:=0)y
)x 
WHERE x.Value<=228000;

408和228000只是示例-我的C#代码构造字符串,然后通过以下方式将其发送到服务器:

StringBuilder statisticQueryString = new StringBuilder("");
// construct statisticQueryString
using (MySqlCommand cmd = new MySqlCommand(statisticQueryString.ToString(), conn))
{
    cmd.Parameters.AddWithValue("r", 0);

    using (MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        // Iterate through the collection of RankResult items...
    }
}

一个示例构造查询(在发送前我将最终查询打印到日志中)由于上述语法错误而失败:

SELECT Rank, Value 
FROM (SELECT @r := @r+1 AS Rank, z.* 
      FROM(SELECT MemberId, Value 
           FROM (SELECT Id, MemberId, Value, CreatedDate, EventId 
                 FROM Scores
                 WHERE (LoadTime IS NULL AND EventId = 408)
                 ORDER BY Value DESC
                ) AS sub 
     )z, 
     (SELECT @r:=0)y
)x 
WHERE x.Value<=228000;

如您所见,构造的查询与我可以在MySql工作台中无错误运行的查询相同。

1 个答案:

答案 0 :(得分:0)

@Uueerdo的评论促使我尝试从C#代码中删除cmd.Parameters.AddWithValue("r", 0);行。这样可以解决错误,并给了我期望的结果。