如何创建一个简单的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
   −> );

使用insert命令在表中插入记录。查询如下-

mysql> insert into ViewDemo values(1,'John',23);

mysql> insert into ViewDemo values(2,'Sam',24);

使用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;
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 //
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)