为什么设置SQL变量会创建错误?

时间:2018-08-23 06:41:27

标签: mysql last-insert-id

以下SQL语句正在创建一条错误消息: “消息:命令执行期间遇到致命错误。” “内部异常:必须定义参数'@LastUserID'。”

如果我直接使用LAST_INSERT_ID()而不是LastUserID,则在执行这种操作时,它始终返回零(因此在第二次插入时失败)。

我没有看到我的语法与mySQL文档中的语法不同。

有人可以帮我吗?

string Query = @"INSERT INTO login (" +
                                    "LOGIN_EMAIL," +
                                    "LOGIN_PASSWORD," +
                                    "LOGIN_SALT," +
                                    "LOGIN_LAST_LOGIN_DATE," +
                                    //         "LOGIN_LAST_LOGIN_LOCATION," +
                                    "LOGIN_ACCOUNT_STATUS," +
                                    "LOGIN_LOGIN_ATTEMPTS," +
                                    "LOGIN_CREATED_DATE) " +
                                "VALUES (" +
                                    "@Parameter2," +
                                    "@Parameter3," +
                                    "@Parameter4," +
                                    "@Parameter5," +
                                    //                                        "@Parameter6," +
                                    "@Parameter6," +
                                    "@Parameter7," +
                                    "@Parameter8); " +
                                "SET @LastUserID = LAST_INSERT_ID(); " + 
                                "INSERT INTO user_role (" +
                                    "USER_ROLE_USER_ID," +
                                    "USER_ROLE_ROLE," +
                                    "USER_ROLE_STATUS," +
                                    "USER_ROLE_CREATED_DATE) " +
                                "SELECT " +
                                    "@LastUserID," +
                                    "@Parameter9," +
                                    "@Parameter10," +
                                    "@Parameter11 " +
                                "FROM dual WHERE NOT EXISTS (SELECT USER_ROLE_USER_ID FROM user_role " +
                                "WHERE USER_ROLE_USER_ID = @LastUserID AND USER_ROLE_ROLE = @Parameter9)";

                    MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);

                oCommand.Transaction = tr;

2 个答案:

答案 0 :(得分:0)

简单修复:将“ $ LastUserID”替换为“ $'LastUserID'”。衣食住行与众不同。

答案 1 :(得分:0)

创建一个过程,在该过程中,您首先执行插入操作,缓存最后插入的ID,然后执行另一个插入操作,如果最后一次插入操作无效,则使用bool打印输出参数。这样您就可以正确调试它。

通常,应避免使用字符串来生成sql命令,否则可能会遇到包含意外字符的参数或被injection击中的麻烦。