views:

1550

answers:

5

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!

A: 

If I understand you correctly, you want to create a stored procedure? http://dev.mysql.com/tech-resources/articles/mysql-storedprocedures.html

Eddy
I don't think he wants to change the data in the database, just apply the change to the results (outside the database).
Elie
Hi - correct, I dont want the data in the database to change. thanks
undefined
and you can't call stored procedure in select part of query.
vaske
+4  A: 

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.

Sunny
+4  A: 
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.

Quassnoi
Hi thanks for your response, where do I write this code... do I need to compile a C program for running a UDF from a windows 2003 server? Do you know of a good tutorial for this or can you please guide me through the process. Many thanks
undefined
Custom functions are written in the MySQL database, just as tables are.
St. John Johnson
A: 

You can't write a user defined function in PHP (or at least not without writing a wrapper that will call your script), as UDFs are loaded as native code.

tstenner