Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write my own mySQL functions to use in mySQL queries?

Can I write a custom function that I can call when making mySQL queries eg.

My database table has fields 'filetype' and 'filename'. I want to perform a function on filename before returning the result.

$query = "SELECT filetype, MY_FUNCTION(filename) FROM table..";
$result = mysql_query($query);
return $result

SO $result now has the new values created by MY_FUNCTION. The original database data will be unchanged.

OK - so it looks like User Defined Functions are the way to go... how do I write my own user defined function? Can I use PHP to write it? Where do I save the function or do I include it in my globals file?

Thanks!

like image 652
undefined Avatar asked Apr 03 '09 15:04

undefined


People also ask

How do I create a custom function in MySQL?

The syntax to create a function in MySQL is: CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ] RETURNS return_datatype BEGIN declaration_section executable_section END; function_name. The name to assign to this function in MySQL.

Can you make functions in MySQL?

MySQL functions can be created by using the CREATE FUNCTION statement. We can call the functions inside the query or simply select the function value.

How do you call a function in a MySQL query?

A function can be called by specifying its name and parameter list wherever an expression of the appropriate data type may be used. To show how stored functions can be called, we'll use the simple stored function shown in Example 10-6.

How do I import a function into MySQL?

In PhpMyAdmin open your DB. After that click on "Export" button. In opening window it should be folowing checkboxes in (if it's not shown select "Custom - display all possible options"): 1) Add DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT; 2) Add CREATE PROCEDURE / FUNCTION / EVENT; Check and export it.


2 Answers

DELIMITER $$

CREATE FUNCTION MY_FUNCTION (FILENAME VARCHAR(255)) RETURNS VARCHAR(255)
DETERMINISTIC
NO SQL
BEGIN
       RETURN SUBSTR(filename, 1, 20);
END
$$


DELIMITER ;

To create the function, you just paste its code (sililar to provided above) in your favorite query tool, like mysql.exe, MySQL Query Browser, phpmysqladmin etc.

You can write UDF's both in C and in SQL. In the latter case, you don't need to have a compiler.

The function I provided as an example is an SQL UDF. It just returns first 20 characters of the filename.

You can use any MySQL functions in an SQL UDF.

like image 152
Quassnoi Avatar answered Sep 30 '22 04:09

Quassnoi


Yes, this is called User Defined Functions (UDF).

And here is a good repository of already pre-build functions, so you can check if something fits your needs.

like image 43
Sunny Milenov Avatar answered Sep 30 '22 03:09

Sunny Milenov