Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL declaring variables

Tags:

mysql

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.

like image 482
55651909-089b-4e04-9408-47c5bf Avatar asked Jul 16 '12 13:07

55651909-089b-4e04-9408-47c5bf


People also ask

Can you declare variables in MySQL?

MySQL allows you to declare two or more variables that share the same data type using a single DECLARE statement. The following example declares two integer variables x and y , and set their default values to zero.

How do I assign a variable in MySQL?

MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.

How do I declare multiple variables in MySQL?

DECLARE var1 int; DECLARE var2 int; DECLARE var3 int; SELECT var1:=id, var2:=foo, var3:=bar from page WHERE name="bob"; CALL someAwesomeSP (var1 , var2 , var3 );

How do I declare a selected variable in MySQL query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


2 Answers

declare variable in MySQL with @ and assign with :=

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

References

  • user defined variables
  • assignment
like image 189
diEcho Avatar answered Oct 05 '22 13:10

diEcho


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();
like image 31
Ike Walker Avatar answered Oct 05 '22 14:10

Ike Walker