【发布时间】:2020-06-24 19:21:20
【问题描述】:
对于mysql-5.7.30,下面的循环语法似乎是无效的。
mysql> SET @r = 6
-> SET @i = 3
-> WHILE @i <= @r DO
-> BEGIN
-> PRINT @i
-> END WHILE;
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 'SET @i = 3
WHILE @i <= @r DO
BEGIN
PRINT @i
END WHILE' at line 2
mysql>
我看到各种格式,例如WHILE i <= r DO 似乎不同的版本,语法差异很小。我该如何解决?
更新:
我什至根据下面的答案创建了一个程序,但你可以看到它失败了。
mysql> CREATE PROCEDURE dowhile()
-> BEGIN
-> DECLARE r INT DEFAULT 4
-> DECLARE i INT DEFAULT 3
-> WHILE i <= r DO
-> SELECT * FROM mdl_user WHERE id=i
-> END WHILE
-> END;
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 'DECLARE i INT DEFAULT 3
WHILE i <= r DO
SELECT * FROM mdl_user WHERE id=i
mysql>
更新:
使用exampleabout分隔符,我写了以下代码,但最后出现错误。
mysql> DELIMITER //
mysql> CREATE PROCEDURE dowhile()
-> BEGIN
-> DECLARE r INT DEFAULT 4;
-> DECLARE i INT DEFAULT 3;
-> WHILE i <= r DO
-> SELECT * FROM mdl_user WHERE id=i;
-> END WHILE;
-> END //
ERROR 1044 (42000): Access denied for user 'moodleuser'@'localhost' to database 'moodle'
更新:
下面的代码也是错误的。
$ mysql -u moodleuser -p moodle
Enter password:
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> CREATE PROCEDURE dowhile()
-> BEGIN
-> DECLARE r INT DEFAULT 4;
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 '' at line 3
【问题讨论】:
标签: mysql sql loops stored-procedures