Dem*_*ele 33 mysql stored-procedures function
我想创建一个简单的MySQL函数,我有这个MySQL程序:
CREATE PROCEDURE getUser(gU INT)
SELECT * FROM Company
WHERE id_number = gU;
CALL getUser(2);
Run Code Online (Sandbox Code Playgroud)
我需要一些帮助,使其成为MySQL函数.在程序中使用函数的优缺点是什么?
Ale*_*das 35
这是一个mysql函数示例.我希望它有所帮助.(我还没有测试过,但应该工作)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
Run Code Online (Sandbox Code Playgroud)
Eri*_*ski 13
打开mysql终端:
el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>
Run Code Online (Sandbox Code Playgroud)
删除该功能(如果已存在)
mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
创建功能
mysql> create function hello(id INT)
-> returns CHAR(50)
-> return 'foobar';
Query OK, 0 rows affected (0.01 sec)
Run Code Online (Sandbox Code Playgroud)
创建一个简单的表来测试它
mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)
Run Code Online (Sandbox Code Playgroud)
在表格中插入三个值
mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
Run Code Online (Sandbox Code Playgroud)
从yar中选择所有值,每次运行我们的函数hello:
mysql> select id, hello(5) from yar;
+------+----------+
| id | hello(5) |
+------+----------+
| 5 | foobar |
| 7 | foobar |
| 9 | foobar |
+------+----------+
3 rows in set (0.01 sec)
Run Code Online (Sandbox Code Playgroud)
对刚刚发生的事情进行言语化和内化:
您创建了一个名为hello的函数,它接受一个参数.该参数被忽略并返回CHAR(50)包含值'foobar'的a.您创建了一个名为yar的表,并为其添加了三行.select语句hello(5)为yar返回的每一行运行函数.
| 归档时间: |
|
| 查看次数: |
147618 次 |
| 最近记录: |