简体   繁体   中英

SQL Server remove part of string between characters

I have emails that look like this:

john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d@gmail.com

I am trying to get this output:

john.doe@gmail.com

I have this so far.... it's close.

SELECT 
    Caller = REPLACE(Caller, 
                 SUBSTRING(Caller, 
                    CHARINDEX('.', Caller), 
                       CASE WHEN CHARINDEX('@', Caller, CHARINDEX('.', Caller)) > 1 THEN
                           CHARINDEX('@', Caller, CHARINDEX('.', Caller)) - CHARINDEX('.', Caller)
                       ELSE
                          LEN(Caller)
                END  ) , '')
FROM 
    some.table

Hmmm. I suspect the string you want to remove is fixed in length. So how about:

select stuff(caller, charindex('@',caller ) - 37, 37, '')

If you have SS 2016 or later, you can use R code to do it - granted I don't know about speed on larger data so be wary if its a production environment. Also be warned Regexp isn't my strongest area so you may want to check that portion.

DECLARE @dummyScript NVARCHAR(1000)  = '
SELECT * FROM 
(VALUES (''john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d@gmail.com''),  
       (''jane whoever 1234453-534343@yahoo.com'') ) t (Email)
'


DECLARE @myRcode NVARCHAR(600)
SET @myRcode = 'OutputDataset <- data.frame(Email_Cleaned = gsub("[0-9]+.+@", "@", InputDataSet$Email))  '


DECLARE @CleanedTable TABLE (Email_Cleaned VARCHAR(500))

INSERT INTO @CleanedTable
EXEC sp_execute_external_script
@language = N'R'
,@script = @myRcode
,@input_data_1 = @dummyScript
,@input_data_1_name = N'InputDataSet'
,@output_data_1_name = N'OutputDataset'



SELECT * FROM @CleanedTable

Here is a simpler method using LEFT() , RIGHT() , and CHARINDEX() functions

DECLARE @Caller VARCHAR(MAX) = 'john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d@gmail.com'

SELECT 
    LEFT(@Caller, CHARINDEX('.', @Caller, CHARINDEX('.', @Caller) + 1) - 1) + RIGHT(@Caller, LEN(@Caller) - CHARINDEX('@', @Caller) + 1) Email

The left side will get all the characters until the second dot, and the right side will get the characters from @ sign to the end of characters.

Try like below

    SELECT 
      REPLACE(CALLER,
      Substring(CALLER, 
        PATINDEX('.[0-9]%@', CALLER),
     PATINDEX('@', CALLER  ) )

          ,'@')

     From Table 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM