Can you use MySQL @ session variables in the C# connector?

安稳与你 提交于 2019-12-08 02:49:52

问题


I have a query that utilizes MySQL session variables (note the @rank variable)

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;

If I try to execute this against the C# MySQL connector, it tries to tell me that I need to declare @rank as an input parameter variable.

Is there any way around this?

Thanks.


回答1:


Hello Allison!

I was facing the same problem recently, but I found that by default, the SQL connection disables the use of variables in queries. To solve this problem you can enable the connection string as follows:

Connection String:

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

You must enter connection parameter Allow User Variables=True to make it work.

I hope I've helped.

Hiago Takaki




回答2:


There is another way if you don't want to make the change global by setting the connection string.

This can be done by surrounding the name with single quotes ' like the following.

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;

It will now be treated as a session variable.



来源:https://stackoverflow.com/questions/16348028/can-you-use-mysql-session-variables-in-the-c-sharp-connector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!