首页 > 解决方案 > while 循环的教程示例对我不起作用

问题描述

我从这个链接尝试一个例子while循环

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside simulated FOR LOOP on TechOnTheNet.com';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done simulated FOR LOOP on TechOnTheNet.com';
GO

但后来我收到这些错误:-

mysql> DECLARE @cnt INT = 0;                                                                                                                      

ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“DECLARE @cnt INT = 0”附近使用正确的语法

mysql> 
mysql> WHILE @cnt < 10
    -> BEGIN
    ->    PRINT 'Inside simulated FOR LOOP on TechOnTheNet.com';
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 'WHILE @cnt < 10
BEGIN
   PRINT 'Inside simulated FOR LOOP on TechOnTheNet.com'' at line 1


mysql>    SET @cnt = @cnt + 1;
Query OK, 0 rows affected (0.00 sec)

mysql> 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 'END' at line 1


mysql> 
mysql> PRINT 'Done simulated FOR LOOP on TechOnTheNet.com';
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 'PRINT 'Done simulated FOR LOOP on TechOnTheNet.com'' at line 1
mysql> GO
ERROR: 
No query specified

标签: mysqlsqlwhile-loop

解决方案


您在使用 MySQL 时从 SQL Server 教程中复制。

MySQL 中的正确版本是:

CREATE PROCEDURE sp_test() 
BEGIN   
  DECLARE cnt INT DEFAULT 0;

  WHILE cnt < 10 DO
    SELECT 'Inside simulated FOR LOOP on TechOnTheNet.com';
    SET cnt = cnt + 1;
  END WHILE;
END//

演示:http ://sqlfiddle.com/#!9/a4fb7c/1 。


推荐阅读