用于修复表中的电话号码问题的SQL查询

Ham*_*han 4 regex sql asp.net sql-server-2005

我有一个包含电话号码列的表.如何输入电话号码没有限制.目前,电话号码采用以下格式

123-456-7890
(123)-456-7890
1234567890
Run Code Online (Sandbox Code Playgroud)

我想更新表格,并以123-456-7890格式显示所有电话号码.我有超过20k的记录.我可以使用SQL Query执行此操作,还是必须在ASP或PHP中使用正则表达式?

编辑:注意最佳答案是修改后的问题,电话号码(123)-456-78790 更改为(123)456-7890

Der*_*omm 7

如果它们严格使用这3种格式中的一种,则可以通过使用SUBSTRING和测试LEN每个项目来轻松地在SQL中完成.

如果还有其他格式,我建议使用更好的文本操作语言,例如.net.

编辑添加:

鉴于您的评论现在只有3种格式,您可以这样做:

declare @t table (x varchar(20))
insert into @t 
select '123-456-7890'
union select '(123)456-7890'
union select '1234567890'

select 
    case 
      when len(x) = 10 then 
        substring(x, 1, 3) + '-' + substring(x, 4, 3) + '-' + substring(x, 7, 4)
      when len(x) = 13 then
        substring(x, 2, 3) + '-' + substring(x, 6, 8)
      else x
    end
from @t
Run Code Online (Sandbox Code Playgroud)