some_bloody_fool
some_bloody_fool

Reputation: 4685

How to select only the characters appearing before a specific symbol in a SQL Select statement

I have strings in a database like this:

[email protected]/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.

Upvotes: 14

Views: 96597

Answers (2)

Izulien
Izulien

Reputation: 413

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 '[email protected]/IMCLientName' then you would receive 'firstname.lastname' as a result.

Upvotes: 6

Ian Nelson
Ian Nelson

Reputation: 58753

DECLARE @email VARCHAR(100)
SET @email = '[email protected]/IMCLientName'

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

Upvotes: 37

Related Questions