What is wrong with my MySQL CASE/WHEN syntax?

折月煮酒 提交于 2019-12-12 17:16:38

问题


I'm trying to learn the ropes of some new MySQL syntax and am having trouble. This should be simple...

I'm following along with the manual here: http://dev.mysql.com/doc/refman/5.5/en/case.html

but I keep getting a syntax error. Here is my routine:

# Drop anonymous accounts, if any
USE mysql;
CASE (SELECT COUNT(*) FROM user WHERE User = '' AND Host = 'localhost') 
 WHEN 1 THEN
  DROP USER ''@'localhost';
  FLUSH PRIVILEGES; 
END CASE;

The error is:

ERROR 1064 (42000): 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 'CASE (SELECT COUNT(*) FROM user WHERE User = '' AND Host = 'localhost')

Thanks in advance.


回答1:


After reviewing your comment regarding the fixed statement but immediate second issue, it was clear that you're not using this within a stored procedure or function. The documentation for flow control statements very subtly states that they need to be within stored procedures/functions.

Update your code to be within a procedure, and then just call the procedure to execute:

USE mysql;

DROP PROCEDURE p;
DELIMITER |
CREATE PROCEDURE p() BEGIN
    CASE (SELECT COUNT(*) FROM user WHERE User = '' AND Host = 'localhost') 
        WHEN 1 THEN
            DROP USER ''@'localhost';
            FLUSH PRIVILEGES;
        ELSE
            SELECT 'no users found!';
    END CASE;
END;
|

CALL p();

Also note that I added a catch-all ELSE block; if you don't catch the value, CASE will throw a "Case not found" warning - which may or may not be desirable.



来源:https://stackoverflow.com/questions/12133272/what-is-wrong-with-my-mysql-case-when-syntax

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