简介
考虑到我不知道数据库,我在 Oracle、PostgresSql 和 MySQL 中实现了这个。
以下是(根据我的经验)最常使用 || 进行连接的 3 个数据库(请参阅:https://www.databasestar.com/sql-concatenate/)。
你需要两件事:
示例(Oracle SQL)
WITH pp AS (
select '30' as country_code_number, '1234' as area_code, '1234567-555' as phone_number from dual
UNION
select '44' as country_code_number, '1234' as area_code, '1234567-555' as phone_number from dual
)
SELECT CONCAT(CASE
WHEN pp.country_code_number = 44 THEN ' '
ELSE concat('+', pp.country_code_number)
END, REGEXP_REPLACE(CONCAT (pp.area_code, pp.phone_number), '[^0-9]+', '')) AS phone_number
FROM pp;
示例(Postgres)
select
CONCAT(
CASE WHEN pp.country_code_number <> '44' then concat('+',pp.country_code_number)
ELSE ' '
END
,
regexp_replace( concat ( pp.area_code , pp.phone_number ) , '[^0-9]+', '', 'g')
) as phone_number from
pp;
链接:https://www.db-fiddle.com/f/p6ziyWyWCGXTCiyiYSSyS8/2
示例(MySQL)
SELECT CONCAT(CASE
WHEN pp.country_code_number = 44 THEN " "
ELSE concat('+', pp.country_code_number)
END, STRIP_NON_DIGIT(CONCAT (pp.area_code, pp.phone_number))) AS phone_number
FROM pp;
DDL
create table pp(
country_code_number varchar(10),
area_code varchar(10),
phone_number varchar(20)
);
insert into pp values('30','210','123-456-789');
insert into pp values('44','210','123-456-789');
DROP FUNCTION IF EXISTS STRIP_NON_DIGIT;
DELIMITER $$
CREATE FUNCTION STRIP_NON_DIGIT(input VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE output VARCHAR(255) DEFAULT '';
DECLARE iterator INT DEFAULT 1;
WHILE iterator < (LENGTH(input) + 1) DO
IF SUBSTRING(input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN
SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
END IF;
SET iterator = iterator + 1;
END WHILE;
RETURN output;
END
$$
链接:https://www.db-fiddle.com/f/p6ziyWyWCGXTCiyiYSSyS8/1