mysql case语法错误,我的MySQL CASE / WHEN语法有什么问题?

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

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值