Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ใช้ตัวแปรใน MySQL แทน Ampersand (&) ของ Oracle

ตัวแปร User-defined Variables ใน MySQL

MySQL ใช้ @variable_name แทน Ampersand (&) ของ Oracle สำหรับผูกตัวแปรในคำสั่ง SQL

ไวยากรณ์

SET @var1 = value1, @var2 = value2, ...;
INSERT INTO table VALUES (@var1, @var2, ...);

ตัวอย่าง

CREATE TABLE Student_Information (
    StudentId INT, StudentName VARCHAR(100),
    StudentAge INT, StudentMarks INT, StudentCountryName VARCHAR(10)
);

SET @Id = 10001, @Name = 'Carol', @Age = 23, @Marks = 89, @CountryName = 'US';
INSERT INTO Student_Information VALUES (@Id, @Name, @Age, @Marks, @CountryName);

ผลลัพธ์

+-----------+-------------+------------+--------------+--------------------+
| StudentId | StudentName | StudentAge | StudentMarks | StudentCountryName |
+-----------+-------------+------------+--------------+--------------------+
| 10001     | Carol       | 23         | 89           | US                 |
+-----------+-------------+------------+--------------+--------------------+

คุณสมบัติ

  • ตัวแปรขึ้นต้นด้วย @ (เช่น @name, @id)
  • Scope: Session-level (หายเมื่อปิด Connection)
  • ไม่ต้อง Declare ก่อนใช้
  • ชนิดข้อมูลถูก Infer อัตโนมัติ

เปรียบเทียบกับ Oracle

OracleMySQL
&variable@variable
DEFINE variable = valueSET @variable = value
SQL*Plus featureNative SQL