i2tutorials

MySQL – Stored Procedure Variables

MySQL – Stored Procedure Variables

 

Variables can be used in the stored procedure to hold input parameters, values inside the block, and immediate results. Variables in a stored procedure have a local scope. A variable must be defined before it can be used within a stored procedure.

Let us now examine how we can declare a variable within a stored procedure.

How to Declare Variables in Stored Procedures

To specify a variable in MySQL, we use the DECLARE keyword. The syntax for declaring a variable is as follows:

DECLARE variable_name datatype(size) [DEFAULT default_value];

Where,

Example

DELIMITER //

CREATE PROCEDURE proc_demo()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE output VARCHAR(100) DEFAULT '';
WHILE i < 10 DO
SET output = CONCAT(output, i , ',');
SET i = i + 1;
END WHILE;
SELECT output;
END //

The above example declares two variables i and output and assigns them default values of 0 and ”, respectively.

my

Using a while loop, we increment the value of i from 0 to 9. In order to create a string of 0 to 9 digits, we used the CONCAT function to concatenate the previous output and the new digit.

It is set to i+1 every time until i reaches 10 and the loop ends.

To print the results, we use the SELECT statement.

As a result of calling the above procedure, we receive the following output:

call proc_demo();

We have achieved the expected result of a string containing digits from 0 to 9.

 

Exit mobile version