How to select only the characters appearing before

2019-02-21 23:44发布

问题:

I have strings in a database like this:

firstname.lastname@email.com/IMCLientName

And I only need the characters that appear before the @ symbol.

I am trying to find a simple way to do this in SQL.

回答1:

DECLARE @email VARCHAR(100)
SET @email = 'firstname.lastname@email.com/IMCLientName'

SELECT SUBSTRING(@email,0, CHARINDEX('@',@email))


回答2:

Building on Ian Nelson's example we could add a quick check so we return the initial value if we don't find our index.

DECLARE @email VARCHAR(100)
SET @email = 'firstname.lastname.email.com/IMCLientName'

SELECT  CASE WHEN CHARINDEX('@',@email) > 0
            THEN SUBSTRING(@email,0, CHARINDEX('@',@email))
            ELSE @email
        END AS email

This would return 'firstname.lastname.email.com/IMCLientName'. If you used 'firstname.lastname@email.com/IMCLientName' then you would receive 'firstname.lastname' as a result.