SQL:格式化电话号码(插入空格)

时间:2016-04-23 19:16:15

标签: mysql sql database

我有一个电话号码的数据库看起来像这样:

0041 123423423
0042 783728492
0043 832792922
0044 738922222

但也有数字看起来像这样:

00432 7462893-99
0042 873946278-100
0041 837227-1234

现在我想将所有电话号码转换为以下格式:

"00[2 digits] [4 digits] [5 digits] [3 digits]"

显然,并非所有电话号码都具有相同的数字位数,但仍应进行格式化。这应该通过SQL来完成(我不认为我有另一种可能性)。我正在使用MySQL。

电话号码示例:

Unformatted: 004912345
Formatted:   0049 1234 5

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该可以帮到你..最后一列是格式

的结果
SELECT
  @number := REPLACE(number,' ','') as minusspace,
  @number := REPLACE(@number,'-','') as minusdash,
  @first := LEFT(@number,4) as first,
  @second := RIGHT(LEFT(@number,8),4) as second,
  @third := RIGHT(LEFT(@number,13),LEAST(LENGTH(@number)-8,5)) as third,
  @fourth := RIGHT(LEFT(@number,16),LEAST(LENGTH(@number)-13,3)) as fourth,
  TRIM(CONCAT(@first,' ',@second,' ',@third,' ',@fourth)) as formatted_phone
FROM phone

sqlfiddle