0

我有一个三库应用(没有一个是我开发的),里面存储了很多电话号码,但是它们的格式不一致(555-5555、(555)555-5555、5555555555、5555555等)在web端,我希望它们始终显示为 555-555-5555。我编写了一个标量函数来清理它们,但它会被称为 OFTEN,我担心它的效率。

你能看看,如果有更好的方法,请告诉我。

ALTER FUNCTION [dbo].[FormatPhone]
(
  @p AS VARCHAR(20)
) RETURNS VARCHAR(12) AS

BEGIN
DECLARE @ret AS VARCHAR(12) = ''
DECLARE @c AS CHAR
DECLARE @i AS INT
DECLARE @stop AS INT

-- loop to grab only digits from @p
SET @i = 1
SET @stop = LEN(@p)
WHILE @i <= @stop
BEGIN
    SET @c = SUBSTRING(@p, @i, 1)
    IF @c >= '0' AND @c <= '9' SET @ret = @ret + @c
    SET @i = @i + 1
END
IF LEN(@ret) = 7 SET @ret = '204' + @ret -- account for forgotten area code

SET @ret = LEFT(@ret, 3) + '-' + SUBSTRING(@ret, 4, 3) + '-' + RIGHT(@ret, 4)

RETURN @ret

谢谢!缺口。

4

3 回答 3

2

你说的是数据清洗。以我的经验(我在一个俄罗斯业务部门进行了一个为期 6 个月的项目,其中大约 90% 都在电话号码格式问题上撞墙),这完全是痛苦的。

我对此的建议是做一次并正确地做;然后将系统放置到位,以防止将来脏数据进入系统。

我们最终做的是让行政办公室的几个女孩手工完成!问题是,如果你做错了,数据就会变得毫无用处。试一试自动解析,看看它会把你带到哪里,但有时人胜过机器。

于 2013-04-12T14:13:08.623 回答
1
  • 替换除数字以外的所有字符
  • 转换为样本 XXX-XXX-XXXX

使用 SUBSTRING,替换 T-SQL

于 2013-04-12T14:09:53.200 回答
0

此函数查看数字/字符串以确定大小和格式,没有循环

CREATE Function [dbo].[FormatPhone] (@PD varchar(50))
RETURNS Varchar(50)
As 
Begin

Declare @F1 As tinyint
Declare @F2 As tinyint
Declare @F3 As tinyint
Declare @F4 As tinyint
Declare @F5 As tinyint
Declare @F6 As tinyint

Declare @NPD As Varchar(50)

Declare @PDLen As tinyint

--Trim any space off the ends
SET @PD = RTRIM(LTRIM(@PD))

--Default just return the data, unless in proper foramt
SET @NPD = @PD

--Check for phone number that all ready has formatting, 
--we are only going to format a 'Pure' set of numbers.
--Check for formating, space 
SET @F1 = CHARINDEX('(', @PD)
SET @F2 = CHARINDEX(')', @PD)
SET @F3 = CHARINDEX('-', @PD)
SET @F4 = CHARINDEX('.', @PD)
SET @F5 = CHARINDEX(' ', @PD)
SET @F6 = @F1 +@F2 + @F3 + @F4 + @F5


IF @F6 = 0
--No formating, figure out the lenght
BEGIN
SET @PDLen = LEN(@PD)

    IF @PDLen = 10  SET @NPD = '('+SUBSTRING(@PD, 1, 3)+') '+SUBSTRING(@PD, 4, 3)+'-'+SUBSTRING(@PD, 7, 4)
    IF @PDLen = 11 AND SUBSTRING(@PD, 1, 1) = '1'  SET @NPD = '('+SUBSTRING(@PD, 2, 3)+') '+SUBSTRING(@PD, 5, 3)+'-'+SUBSTRING(@PD, 8, 4)
    IF @PDLen = 7  SET @NPD = '(   ) '+SUBSTRING(@PD, 1, 3)+'-'+SUBSTRING(@PD, 4, 4)

END

RETURN @NPD

END
于 2014-06-23T17:28:04.320 回答