Using String functions in a user-defined function : Buildin Functions « Procedure Function « SQL / MySQL






Using String functions in a user-defined function

  
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE FUNCTION myFunction
    ->    (in_string      VARCHAR(255),
    ->     in_find_str    VARCHAR(20),
    ->     in_repl_str    VARCHAR(20))
    ->
    ->   RETURNS VARCHAR(255)
    -> BEGIN
    ->   DECLARE l_new_string VARCHAR(255);
    ->   DECLARE l_find_pos   INT;
    ->
    ->   SET l_find_pos=INSTR(in_string,in_find_str);
    ->
    ->   IF (l_find_pos>0) THEN
    ->     SET l_new_string=INSERT(in_string,l_find_pos,LENGTH(in_find_str),in_repl_str);
    ->   ELSE
    ->     SET l_new_string=in_string;
    ->   END IF;
    ->   RETURN(l_new_string);
    ->
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql> select myFunction('ABC','A','Z');
+---------------------------+
| myFunction('ABC','A','Z') |
+---------------------------+
| ZBC                       |
+---------------------------+
1 row in set (0.00 sec)

mysql> drop function myFunction;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>

          
  








Related examples in the same category

1.Check MySQL version
2.Call buildin math function in your procedure
3.Use Build-in SUM function in a procedure
4.Return the file size by using the LOAD_FILE function
5.An example of a LOOP: test(n) returns once again a string with n asterisks.