MYSQL declaring variables

后端 未结 2 986
猫巷女王i
猫巷女王i 2020-12-01 16:03

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          


        
相关标签:
2条回答
  • 2020-12-01 16:50

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

    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.

    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();
    
    0 讨论(0)
  • 2020-12-01 16:53

    declare variable in MySQL with @ and assign with :=

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

    References

    • user defined variables
    • assignment
    0 讨论(0)
提交回复
热议问题