ใช้ SELECT CASE ... INTO @variable เพื่อเก็บผลลัพธ์เงื่อนไขลงใน User-Defined Variable
ตัวอย่างการใช้งาน
1. สร้างตารางและแทรกข้อมูล
mysql> create table DemoTable
-> (
-> Num1 int,
-> Num2 int
-> );
Query OK, 0 rows affected (0.65 sec)
mysql> insert into DemoTable values(10,30);
Query OK, 1 row affected (0.11 sec)
2. ใช้ SELECT CASE เก็บค่าลงตัวแปร @s
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)
3. ตรวจสอบค่าตัวแปร
mysql> select @s;
ผลลัพธ์
+-------+ | @s | +-------+ | Lower | +-------+
รูปแบบ CASE ทั้งสองแบบ
Simple CASE
CASE expr WHEN val1 THEN result1 WHEN val2 THEN result2 ELSE default END
Searched CASE (ใช้ในตัวอย่าง)
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default END
หมายเหตุ: ตัวแปร User-Defined Variable (@var) มีขอบเขตใน Session เดียวเท่านั้น