salix/db/routines/pbx/functions/phone_format.sql

37 lines
833 B
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `pbx`.`phone_format`(vPhone VARCHAR(255))
RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
BEGIN
DECLARE vI INT DEFAULT 0;
DECLARE vChr VARCHAR(1);
DECLARE vLen INT DEFAULT LENGTH(vPhone);
DECLARE vNewPhone VARCHAR(255) DEFAULT '';
WHILE vI < vLen
DO
SET vChr = SUBSTR(vPhone, vI + 1, 1);
IF vChr REGEXP '^[0-9]$'
THEN
SET vNewPhone = CONCAT(vNewPhone, vChr);
ELSEIF vChr = '+' AND vI = 0
THEN
SET vNewPhone = CONCAT(vNewPhone, '00');
END IF;
SET vI = vI + 1;
END WHILE;
IF vNewPhone REGEXP '^0+$' OR vNewPhone = '' THEN
RETURN NULL;
END IF;
IF vNewPhone REGEXP '^0034' THEN
SET vNewPhone = SUBSTR(vNewPhone, 5);
END IF;
RETURN vNewPhone;
END$$
DELIMITER ;