
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements