Storing value from a MySQL SELECT statement to a variable?



Let us first create a table −

mysql> create table DemoTable631 (    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentName varchar(100) ); Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable631(StudentName) values('John Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable631(StudentName) values('Adam Smith'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable631(StudentName) values('David Miller'); Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable631;

This will produce the following output −

+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 1 | John Smith | | 2 | Adam Smith | | 3 | David Miller | +-----------+--------------+ 3 rows in set (0.00 sec)

Following is the query to store value from select to a variable −

mysql> set @fullName=(select StudentName from DemoTable631 where StudentId=2); Query OK, 0 rows affected (0.00 sec)

Now you can display the value of a variable −

mysql> select @fullName;

This will produce the following output −

+------------+ | @fullName | +------------+ | Adam Smith | +------------+ 1 row in set (0.00 sec)
Updated on: 2019-08-23T07:54:46+05:30

677 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements