14

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.

Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
some_bloody_fool
  • 4,605
  • 14
  • 37
  • 46

2 Answers2

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

SELECT SUBSTRING(@email,0, CHARINDEX('@',@email))
Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
6

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.

Izulien
  • 363
  • 1
  • 4
  • 10