如何建立一個簡單的MySQL函式?


您可以使用 create function 命令建立函式。語法如下:

delimiter //
DROP FUNCTION if exists yourFunctionName;
CREATE FUNCTION yourFunctionName(Parameter1,...N) returns type
BEGIN
# declaring variables;
# MySQL statementns
END //
delimiter ;

首先,我們將建立一個表並在表中新增一些記錄。之後,將建立一個簡單的函式。以下是建立表的查詢:

mysql> create table ViewDemo
   −> (
   −> Id int,
   −> Name varchar(200),
   −> Age int
   −> );
Query OK, 0 rows affected (0.58 sec)

使用 insert 命令在表中插入記錄。查詢如下:

mysql> insert into ViewDemo values(1,'John',23);
Query OK, 1 row affected (0.15 sec)

mysql> insert into ViewDemo values(2,'Sam',24);
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下:

mysql> select *from ViewDemo;

以下是輸出:

+------+------+------+
| Id   | Name | Age  |
+------+------+------+
|    1 | John | 23   |
|    2 | Sam  | 24   |
+------+------+------+
2 rows in set (0.00 sec)

現在我們將建立一個函式,該函式接收一個整數引數並返回字串。此函式的目的是搜尋具有給定 ID 的記錄。如果給定的 ID 與表 ID 匹配,則返回名稱,否則將顯示“未找到”之類的錯誤訊息。

函式如下:

mysql> SET GLOBAL log_bin_trust_function_creators = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> drop function if exists searchRecord;
   ->
   -> create function searchRecord(yourId int) returns char(100)
   -> begin
   -> declare Name1 char(100) default "No Name Found For This Id";
   -> select Name into Name1 from ViewDemo where Id =yourId;
   -> return Name1;
   -> end //
Query OK, 0 rows affected (0.21 sec)
Query OK, 0 rows affected (0.33 sec)
mysql> delimiter ;

現在檢查函式是否可以使用給定 ID 工作。

**情況 1** - 給定 ID 存在。

查詢如下:

mysql> select searchRecord(2) as Found;

以下是輸出:

+-------+
| Found |
+-------+
| Sam   |
+-------+
1 row in set (0.00 sec)

**情況 2** - 給定 ID 不存在。

查詢如下:

mysql> select searchRecord(100) as Found;

以下是顯示記錄不存在的輸出:

+---------------------------+
| Found                     |
+---------------------------+
| No Name Found For This Id |
+---------------------------+
1 row in set (0.00 sec)

更新於: 2019年7月30日

525 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.