How can we use SET statement to assign a SELECT result to a MySQL user variable?

MySQLMySQLi Database

For using the SET statement to assign a SELECT result to a user variable we need to write the SELECT statement as a subquery within parentheses. The condition is that the SELECT statement must have to return a single value. To make it understand we are using the data from ‘Tender’ table which is as follows −

mysql> select * from Tender;
+----+---------------+--------------+
| Sr | CompanyName   | Tender_value |
+----+---------------+--------------+
| 1  | Abc Corp.     | 250.369003   |
| 2  | Khaitan Corp. | 265.588989   |
| 3  | Singla group. | 220.255997   |
| 4  | Hero group.   | 221.253006   |
| 5  | Honda group   | 225.292266   |
+----+---------------+--------------+
5 rows in set (0.04 sec)

Now, in the following query, we are setting the maximum value, after rounding it up to 2 decimal point, of tender_value to the variable @Val_Max.

mysql> SET @Val_Max = (SELECT ROUND(MAX(tender_value),2) from tender);
Query OK, 0 rows affected (0.00 sec)

mysql> Select @Val_Max;
+----------+
| @Val_Max |
+----------+
| 265.59   |
+----------+
1 row in set (0.00 sec)
raja
Published on 20-Feb-2018 15:21:41
Advertisements