To declare a variable, use DECLARE in a MySQL stored procedure. Let us first create a table −
mysql> create table DemoTable2034 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentAge int -> ); Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2034(StudentName,StudentAge) values('Chris',23); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable2034(StudentName,StudentAge) values('David',21); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2034(StudentName,StudentAge) values('Robert',25); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2034(StudentName,StudentAge) values('Mike',19); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2034;
This will produce the following output −
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Chris | 23 | | 2 | David | 21 | | 3 | Robert | 25 | | 4 | Mike | 19 | +-----------+-------------+------------+ 4 rows in set (0.00 sec)
Here is the query to create a stored procedure and store the above table’s column value in a stored procedure variable −
mysql> delimiter // mysql> create procedure select_into_variable(id int) -> begin -> declare name varchar(50); -> select StudentName into name from DemoTable2034 where StudentId=id; -> select concat('Your Name is= ',name); -> end -> // Query OK, 0 rows affected (0.09 sec) mysql> delimiter ;
Call the stored procedure −
mysql> call select_into_variable(4);
This will produce the following output −
+-------------------------------+ | concat('Your Name is= ',name) | +-------------------------------+ | Your Name is= Mike | +-------------------------------+ 1 row in set (0.04 sec) Query OK, 0 rows affected (0.06 sec)