Perform MySQL SELECT INTO user-defined variable

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1483
   -> (
   -> Salary int
   -> );
Query OK, 0 rows affected (0.41 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1483 values(100);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1483 values(500);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1483 values(400);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1483;

This will produce the following output −

+--------+
| Salary |
+--------+
|    100 |
|    500 |
|    400 |
+--------+
3 rows in set (0.00 sec)

Following is the query to perform select into user-defined variable −

mysql> select sum(Salary) into @TotalSalary from DemoTable1483;
Query OK, 1 row affected (0.00 sec)

Now display the value of variable −

mysql> select @TotalSalary;

This will produce the following output −

+--------------+
| @TotalSalary |
+--------------+
|         1000 |
+--------------+
1 row in set (0.00 sec)
raja
Published on 10-Dec-2019 08:10:31
Advertisements