1

我使用MySQL 我有一个 mysql 表。
我想选择所有带有行号的记录。
为此,我使用这个 sql 命令。

SELECT @row := @row + 1 as row, t.* FROM t_persons t, (SELECT @row := 0) r

但是当我尝试运行命令并将数据加载到数据表中时,如下所示

DataTable dt = new DataTable();
command.CommandText = sql;
adapter.SelectCommand = command;
adapter.Fill(dt);

它给出了一个错误,例如在命令执行期间遇到的致命错误。
但是当我在 phpmyadmin 中尝试这个命令时它工作正常。那么问题是什么。以及如何解决。谢谢...

4

2 回答 2

3

这实际上是 C# 错误,而不是 MySQL 错误。C# 看到 @ 并假设您要使用参数化查询。

添加

;Allow User Variables=True

到您的连接字符串将修复它。

在此处找到如何在 .NET MySqlCommand 中使用 MySql 用户定义变量?

于 2012-11-30T21:34:14.687 回答
-1

It looks like completely valid MySQL implementation of MySQL Variables within a query. You pre-declare them with your select @row := 0 as an "r" alias. It think the problem is that you are calling the final column name "row" which may be reserved. Just for grins, change to:

@row := @row + 1 as myRow

OR... change your variable from @row to @varRow (variable Row)... or a combination of both...

@varRow := @varRow +1 as myRow

I have no idea who down-voted the answer, but what you are doing is quite normal with MySQL, and I've done it MANY TIMES as can be seen through MANY of my posted answers here at s/o.
I would then try to retrieve the columns by the table FIRST, then the @vars columns... don't know if its something within the engine to get a valid record entry before trying to write the @var...

SELECT 
      t.*,
      @varRow := @varRow + 1 as myRow
   FROM 
      t_persons t, 
      (SELECT @varRow := 0) r
于 2012-05-29T13:14:47.087 回答