如何创建一个简单的 MySQL 函数?
mysqlmysqli database
您可以使用 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)