MySQL 如何创建一个简单的函数
可以使用create function命令创建函数。语法如下:-
delimiter //
DROP FUNCTION if exists yourFunctionName;
CREATE FUNCTION yourFunctionName(Parameter1,...N) returns type
BEGIN
# 声明变量;
# MySQL语句
END //
delimiter ;
首先,我们将创建一张表格,在表格中添加一些记录。然后,创建一个简单函数。以下是创建表格的查询语句:-
mysql> create table ViewDemo
−> (
−> Id int,
−> Name varchar(200),
−> Age int
−> );
查询OK,0行受到影响(0.58秒)
使用插入命令在表格中插入记录。查询语句如下:-
mysql> insert into ViewDemo values(1,'John',23);
查询OK,1行受到影响(0.15秒)
mysql> insert into ViewDemo values(2,'Sam',24);
查询OK,1行受到影响(0.15秒)
使用select语句显示表格中的所有记录。查询语句如下:-
mysql> select *from ViewDemo;
以下是输出结果:-
+------+------+------+
| Id | Name | Age |
+------+------+------+
| 1 | John | 23 |
| 2 | Sam | 24 |
+------+------+------+
2行被发现(0.00秒)
现在,我们将创建一个以整数参数为输入并返回字符串的函数。这个函数的目的是寻找具有给定ID的记录。如果给定ID与表格ID相匹配,它将返回名称,否则它将给出一个错误信息如未找到。
函数如下:-
mysql> SET GLOBAL log_bin_trust_function_creators = 1;
查询OK,0行受到影响(0.00秒)
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 //
查询OK,0行受到影响(0.21秒)
查询OK,0行受到影响(0.33秒)
mysql> delimiter ;
现在检查使用给定ID的函数是否正常工作。
Case 1 − 当给定的ID存在时。
查询语句如下:-
mysql> select searchRecord(2) as Found;
以下是输出结果:-
+ -------+
| Found |
+-------+
| Sam |
+-------+
1行被发现(0.00秒)
Case 2 − 当给定的ID不存在时。
查询语句如下:-
mysql> select searchRecord(100) as Found;
以下是输出结果,显示记录不存在:-
+---------------------------+
| Found |
+---------------------------+
| No Name Found For This Id |
+---------------------------+
1行被发现(0.00秒)
阅读更多:MySQL 教程
极客教程