MySQL 如何声明普通查询的变量
您可以使用@任何变量名称声明变量,它是一个会话变量。要创建会话变量,您需要使用SET命令。
语法如下
SET @anyVariableName:=anyValue;
您可以使用DECLARE命令声明局部变量。语法如下
DECLARE yourVariableName datatype
您可以在创建变量时设置默认值。语法如下
DECLARE yourVariableName datatype default ‘yourValue’
这是会话变量的演示。为了理解它,让我们创建一个表。
创建表的查询如下
mysql> create table SessionVariableDemo
-> (
-> EmployeeId varchar(10),
-> EmployeeName varchar(30),
-> EmployeeAge int
-> );
Query OK, 0 rows affected (0.70 sec)
使用insert命令在表中插入一些记录。查询如下
mysql> insert into SessionVariableDemo values('EMP-101','Carol',30);
Query OK, 1 row affected (0.20 sec)
mysql> insert into SessionVariableDemo values('EMP-102','John',26);
Query OK, 1 row affected (0.20 sec)
mysql> insert into SessionVariableDemo values('EMP-103','Bob',25);
Query OK, 1 row affected (0.19 sec)
mysql> insert into SessionVariableDemo values('EMP-104','Sam',32);
Query OK, 1 row affected (0.14 sec)
mysql> insert into SessionVariableDemo values('EMP-105','Mike',35);
Query OK, 1 row affected (0.11 sec)
mysql> insert into SessionVariableDemo values('EMP-106','David',33);
Query OK, 1 row affected (0.15 sec)
使用select语句显示表中的所有记录。查询如下
mysql> select *from SessionVariableDemo;
以下是输出结果
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| EMP-101 | Carol | 30 |
| EMP-102 | John | 26 |
| EMP-103 | Bob | 25 |
| EMP-104 | Sam | 32 |
| EMP-105 | Mike | 35 |
| EMP-106 | David | 33 |
+------------+--------------+-------------+
6 rows in set (0.00 sec)
现在,使用SET命令创建会话变量。之后,我们将在查询中使用此变量来获取所有年龄大于30岁的员工记录。
使用SET命令创建会话变量,如下
mysql> set @AgeGreaterThan30:=30;
Query OK, 0 rows affected (0.00 sec)
以下是使用会话变量获取年龄大于30的员工记录的查询
mysql> select *from SessionVariableDemo where EmployeeAge > @AgeGreaterThan30;
以下是输出结果
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| EMP-104 | Sam | 32 |
| EMP-105 | Mike | 35 |
| EMP-106 | David | 33 |
+------------+--------------+-------------+
3 rows in set (0.00 sec)
阅读更多:MySQL 教程