Créer une fonction MySQL
Les fonctions ont été introduites dans MySQL 5, tout comme les procédures stockées et le trigger. À la différence des procédures stockées, les fonctions ne sont pas destinées à effectuer un traitement logique sur les données (un traitement métier propre à une application), mais elles servent à enrichir les fonctions natives proposées par MySQL comme LENGTH.
Les fonctions s'écrivent en langage SQL, le même langage que celui utilisé dans les procstock et les trigger, mais une fonction doit impérativement retourner un résultat via la commande RETURN.
Voici par exemple une excellente fonction slugify que j'utilise très souvent, qui sert à nettoyer et normaliser une chaîne de caractère en SQL (ce qu'on appelle un slug dans wordpress) :
Cette page peut vous intéresser : aperçu avant impression dans excel à lire tout de suite !
DELIMITER //
CREATE DEFINER=`root`@`localhost` FUNCTION `slugify`(dirty_string VARCHAR(200)) RETURNS VARCHAR(200) CHARSET latin1 DETERMINISTIC
BEGIN
DECLARE x, y , z Int;
DECLARE temp_string, allowed_chars, new_string VARCHAR(200);
DECLARE is_allowed Bool;
DECLARE c, check_char VARCHAR(1);
SET allowed_chars = "abcdefghijklmnopqrstuvwxyz0123456789-";
SET temp_string = dirty_string;
SELECT temp_string Regexp('&') INTO x;
IF x = 1 THEN
SET temp_string = REPLACE(temp_string, '&', ' and ');
END IF;
SELECT temp_string Regexp('[^a-z0-9]+') INTO x;
IF x = 1 THEN
SET z = 1;
While z <= Char_length(temp_string) Do
SET c = Substring(temp_string, z, 1);
SET is_allowed = False;
SET y = 1;
Inner_Check: While y <= Char_length(allowed_chars) DO
IF (STRCMP(ASCII(SUBSTRING(allowed_chars,y,1)), ASCII(c)) = 0) THEN
SET is_allowed = True;
LEAVE Inner_Check;
END IF;
SET y = y + 1;
End While;
IF is_allowed = False THEN
SET temp_string = REPLACE(temp_string, c, '-');
END IF;
SET z = z + 1;
END WHILE;
END IF;
SELECT temp_string Regexp("^-|-$|'") INTO x;
IF x = 1 THEN
SET temp_string = REPLACE(temp_string, "'", '');
SET z = Char_length(temp_string);
SET y = Char_length(temp_string);
Dash_check: WHILE z > 1 Do
IF STRCMP(SUBSTRING(temp_string, -1, 1), '-') = 0 THEN
SET temp_string = Substring(temp_string,1, y-1);
SET y = y - 1;
ELSE
LEAVE Dash_check;
END IF;
SET z = z - 1;
End While;
END IF;
REPEAT
SELECT temp_string Regexp("--") INTO x;
IF x = 1 THEN
SET temp_string = REPLACE(temp_string, "--", "-");
END IF;
Until x <> 1 END REPEAT;
RETURN temp_string;
END//
DELIMITER ;
source: http://nastyhabit.wordpress.com/2008/09/25/mysql-slug-maker-function-aka-the-slugifier/
Encore faim ? allez lire ça : enseigne de casino !




