select left(emailaddress, len(emailaddress) - charindex('@', emailaddress))
I am getting the result below:
foo@ma
Please correct the select statement below. I need to do this with tones of email addresses and extract the username ONLY.
select left(emailaddress, len(emailaddress) - charindex('@', emailaddress))
I am getting the result below:
foo@ma
Please correct the select statement below. I need to do this with tones of email addresses and extract the username ONLY.
You're inadvertently re-implementing "right" there :)
Try this:
select left(emailaddress, charindex('@', emailaddress) - 1)
It seeks the position of the @
, and takes the number of characters up to but not including (that's the - 1
) the @
symbol.
Be careful with strings that don't have an @
though; you'll end up an empty string.
Just a guess. I don't have any access to sql-server, not a familiarity with it. But...
Have you tried:
select left(emailaddress, charindex('@', emailaddress))
If you need to do it with tons (or tonnes but certainly not tones) of email addresses and/or you're doing it frequently, the right time to do it is when the data enters the table (by using an insert/update trigger) and splitting it into two columns at that point. That way, it only happens when needed, not every time you do a select on the table.
Data is almost always read far more often than written so, by splitting at insertion/update time, you minimize the amount of work to be done. Per-row functions never scale well as your tables get bigger and it's a much smaller cost to simply concatenate two columns than to split them based on a character separator.
The other answers already tell you how to do the split. It's my contention that you're doing it at the wrong time. Of course, if a schema change is out of the question, just ignore this response. But, in my opinion, that would be the best way to go.