while循环的教程示例对我不起作用

时间:2019-07-02 05:09:07

标签: mysql sql while-loop

我正在尝试从此link

进行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;                                                                                                                      

错误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

1 个答案:

答案 0 :(得分:0)

您正在使用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