Clever-1945
12/1/2017 - 5:31 AM

getCorrectPhone.sql #ELMA

getCorrectPhone.sql #ELMA

/*create procedure getCorrectPhone as
begin
  print 'placeholder'
end
go
*/

/*
alter procedure getCorrectPhone(@phone varchar(1024)) 
as
    IF @phone IS NULL
    BEGIN  
        print null;
        return;
    END  

    IF CHARINDEX ( '/'  , @phone) > 0 
    BEGIN
        select @phone = SUBSTRING ( @phone ,1 , CHARINDEX ( '/'  , @phone) - 1 );
    END
    IF CHARINDEX ( '\'  , @phone) > 0 
    BEGIN
        select @phone = SUBSTRING ( @phone ,1 , CHARINDEX ( '\'  , @phone) - 1 );
    END
    select @phone = REPLACE(@phone, '\D', '');
    --select @phone = ltrim(rtrim(@phone));

    print @phone;
    return;
go
*/

--drop function dbo.getCorrectPhone

alter FUNCTION dbo.getCorrectPhone (@phone VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    IF @phone IS NULL
    BEGIN  
        return null;
    END  

    IF CHARINDEX ( '/'  , @phone) > 0 
    BEGIN
        select @phone = SUBSTRING ( @phone ,1 , CHARINDEX ( '/'  , @phone) - 1 );
    END
    IF CHARINDEX ( '\'  , @phone) > 0 
    BEGIN
        select @phone = SUBSTRING ( @phone ,1 , CHARINDEX ( '\'  , @phone) - 1 );
    END
        
    WHILE (PATINDEX('%[^0-9.]%', @phone)) > 0
    BEGIN
       select @phone = STUFF(@phone, PATINDEX('%[^0-9.]%', @phone),1, '');
    END
    
    --select @phone = ltrim(rtrim(@phone));
    if LEN(@phone) > 10
    BEGIN
        select @phone = SUBSTRING ( @phone ,(LEN(@phone) - 10 ) + 1 , 10 );
        return @phone;
    END

    DECLARE @code varchar(1028);
    SET @code = '8332';

    if (LEN(@phone)  + LEN(@code)) < 10
    BEGIN
        return null;
    END

    if LEN(@phone) < 10
    BEGIN
       select @phone =  (SUBSTRING ( @code , 1 , 10 + LEN(@phone) ) + @phone);
    END
    
    return @phone;
END