Potresti creare una funzione custom direttamente in mysql.
http://dev.mysql.com/doc/refman/5.0/...procedure.html