你能在C#连接器中使用MySQL @ session变量吗?

时间:2013-05-02 21:28:36

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

我有一个利用MySQL会话变量的查询(注意@rank变量)

SELECT Rank, UserId, CurrentVDOT
FROM
    (
        SELECT @rank := @rank + 1 AS Rank, UserId, MaxVDOT AS CurrentVDOT
        FROM
            (
                SELECT UserId, MAX(VDOT) AS MaxVDOT
                FROM
                    (
                        SELECT U.UserId, U.VDOT
                        FROM
                            (
                                SELECT UserId, MAX(Created) AS Created
                                FROM UserVDOT
                                GROUP BY UserId
                            ) G
                        INNER JOIN UserVDOT U
                        ON U.UserId = G.UserId
                            AND U.Created = G.Created
                    ) M
                GROUP BY UserId
                ORDER BY MaxVDOT DESC
            ) R, (SELECT @rank := 0) foo
    ) F
WHERE F.UserId = @UserId;

如果我尝试对C#MySQL连接器执行此操作,它会尝试告诉我需要将@rank声明为输入参数变量。

有什么方法吗?

感谢。

2 个答案:

答案 0 :(得分:8)

  

Hello Allison!

     

我最近遇到了同样的问题,但我发现默认情况下   SQL连接禁用查询中变量的使用。要解决   您可以按如下方式启用连接字符串:

连接字符串:

server=192.168.0.0;password=root;User Id=root;Persist Security Info=True;database=my_db;Allow User Variables=True

您必须输入连接参数允许用户变量= True 才能使其正常工作。

  

我希望我能帮到你。

     

Hiago Takaki

答案 1 :(得分:2)

如果您不想通过设置连接字符串使更改成为全局,还有另一种方法。

这可以通过使用单引号'包围名称来完成,如下所示。

SELECT Rank, UserId, CurrentVDOT
FROM
    (
        SELECT @'rank' := @'rank' + 1 AS Rank, UserId, MaxVDOT AS CurrentVDOT
        FROM
            (
                SELECT UserId, MAX(VDOT) AS MaxVDOT
                FROM
                    (
                        SELECT U.UserId, U.VDOT
                        FROM
                            (
                                SELECT UserId, MAX(Created) AS Created
                                FROM UserVDOT
                                GROUP BY UserId
                            ) G
                        INNER JOIN UserVDOT U
                        ON U.UserId = G.UserId
                            AND U.Created = G.Created
                    ) M
                GROUP BY UserId
                ORDER BY MaxVDOT DESC
            ) R, (SELECT @'rank' := 0) foo
    ) F
WHERE F.UserId = @UserId;

现在将它视为会话变量。