MYSQL 声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11505522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:11:00  来源:igfitidea点击:

MYSQL declaring variables

mysql

提问by 55651909-089b-4e04-9408-47c5bf

I don't get what is wrong with this script

我不明白这个脚本有什么问题

BEGIN
DECLARE crs INT DEFAULT 0;

WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;

I want it to insert 10 values into the table continent but there is an error at the second line.

我希望它在表大洲中插入 10 个值,但第二行有错误。

回答by diEcho

declare variable in MySQL with @and assign with :=

在 MySQL 中声明变量@并赋值:=

SET @crs = 0; // declaration
--here your query
@crs := @crs+1 // assignment

References

参考

回答by Ike Walker

MySQL does not support the execution of anonymous blocks of stored procedure code.

MySQL 不支持匿名存储过程代码块的执行。

You need to create a stored procedure including that code and then invoke it.

您需要创建一个包含该代码的存储过程,然后调用它。

Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.

此外,您在插入语句的末尾缺少分号。我修好了。您可能还想使用 concat() 而不是 + 来生成名称,但我会将更改留给您。

Create the procedure:

创建过程:

DELIMITER $$

DROP PROCEDURE IF EXISTS insert_ten_rows $$

CREATE PROCEDURE insert_ten_rows () 
    BEGIN
        DECLARE crs INT DEFAULT 0;

        WHILE crs < 10 DO
            INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
            SET crs = crs + 1;
        END WHILE;
    END $$

DELIMITER ;

Invoke the procedure:

调用程序:

CALL insert_ten_rows();