ใช้คำสั่ง SET สำหรับการกำหนดค่าตัวแปรชั่วคราว (User-defined variables)
ไวยากรณ์
SET @anyVariableName = (SELECT yourColumnName FROM yourTableName WHERE yourCondition);
สร้างตารางตัวอย่าง
mysql> create table tempVariableAssignment (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20),
-> Age int
-> );
Query OK, 0 rows affected (0.59 sec)
เพิ่มข้อมูลตัวอย่าง
mysql> insert into tempVariableAssignment(Name,Age) values('John',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);
Query OK, 1 row affected (0.17 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);
Query OK, 1 row affected (0.13 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('David',19);
Query OK, 1 row affected (0.19 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);
Query OK, 1 row affected (0.19 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from tempVariableAssignment;
ผลลัพธ์:
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | John | 25 | | 2 | Carol | 26 | | 3 | Sam | 28 | | 4 | David | 19 | | 5 | Bob | 23 | +----+-------+------+ 5 rows in set (0.00 sec)
วิธีที่ 1: ใช้ SET กับ Subquery
mysql> set @findAge = (select Age from tempVariableAssignment where Id=4); Query OK, 0 rows affected (0.02 sec) mysql> select @findAge;
ผลลัพธ์:
+----------+ | @findAge | +----------+ | 19 | +----------+ 1 row in set (0.01 sec)
วิธีที่ 2: ใช้ SELECT ... INTO
mysql> select Age INTO @anotherAge from tempVariableAssignment where Id=4; Query OK, 1 row affected (0.00 sec) mysql> select @anotherAge;
ผลลัพธ์:
+-------------+ | @anotherAge | +-------------+ | 19 | +-------------+ 1 row in set (0.00 sec)
คำอธิบายเพิ่มเติม
- ตัวแปรที่ขึ้นต้นด้วย
@เรียกว่า User-defined variables มีขอบเขตอยู่ในเซสชัน (session-scoped) - ตัวแปรจะหายไปเมื่อปิดการเชื่อมต่อ
- สามารถใช้ใน stored procedures, triggers, และ prepared statements ได้
- ชนิดข้อมูลของตัวแปรจะถูกกำหนดอัตโนมัติจากค่าที่กำหนด