Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 306
some_bloody_fool Avatar asked Nov 28 '11 16:11

some_bloody_fool


1 Answers

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.

like image 122
Izulien Avatar answered Sep 30 '22 05:09

Izulien