Store a variable with the result of a MySQL SELECT CASE?


For this, use SELECT CASE. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Num1 int,
   -> Num2 int
   -> );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,30);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------+------+
| Num1 | Num2 |
+------+------+
|   10 |   30 |
+------+------+
1 row in set (0.00 sec)

Following is the query to store a variable with the result of a SELECT CASE.−

mysql> select case
   -> WHEN Num1=Num2 THEN "Equal"
   -> WHEN Num1 > Num2 THEN "Greater"
   -> WHEN Num1 < Num2 THEN "Lower" end
   -> from DemoTable
   -> into @s;
Query OK, 1 row affected (0.01 sec)

Let us check the value in the above variable.

mysql> select @s;

Output

This will produce the following output −

+-------+
| @s    |
+-------+
| Lower |
+-------+
1 row in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements