There is no such function in MySQL, but you can create your own saved function. The main difficulty here is that the number of parameters passed to the function can vary.
One possible solution would be to pass a string with a set of values ββseparated by a separator using the CONCAT_WS function (see the CONCAT_WS () function ). You will also need to define a line separator if your separator is included in one of the set values.
Here is an example script:
DELIMITER |;
CREATE FUNCTION MY_COALESCE (
p_set_string TEXT
, p_delimiter CHAR (1)
) RETURNS TEXT
DETERMINISTIC
BEGIN
RETURN SUBSTRING_INDEX (SUBSTRING_INDEX (
REPLACE (REPLACE (
CONCAT (p_delimiter, p_set_string, p_delimiter)
, CONCAT (p_delimiter, '0', p_delimiter), '')
, CONCAT (p_delimiter, p_delimiter), '')
, p_delimiter, 2), p_delimiter, -1)
;
END
|;
DELIMITER;
SET @ separator = ',', @delimiter = '$';
SELECT
MY_COALESCE (
CONCAT_WS (CONCAT (@ delimiter, @ separator, @ delimiter), 0, '', 'banana')
, @ delimiter
) as fruit
;
When you run the previous script, you get the following output:
MySQL> --------------
MySQL> SET @ separator = ',', @delimiter = '$'
MySQL> --------------
MySQL>
MySQL> Query OK, 0 rows affected (0.00 sec)
MySQL>
MySQL> --------------
MySQL> SELECT
MySQL> MY_COALESCE (
MySQL> CONCAT_WS (CONCAT (@ delimiter, @ separator, @ delimiter), 0, '', 'banana')
MySQL>, @ delimiter
MySQL>) as fruit
MySQL> --------------
MySQL>
MySQL> + -------- +
MySQL> | fruit |
MySQL> + -------- +
MySQL> | banana |
MySQL> + -------- +
MySQL> 1 row in set (0.02 sec)
You can, of course, adapt the value of the line separator so that there are no conflicts with your set values.