如何在MySQL普通查詢中宣告變數?


您可以使用`@anyVariablename`宣告變數,這是一個會話變數。要建立會話變數,您需要使用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)

更新於:2019年7月30日

4K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.