IndexOf function in T-SQL IndexOf function in T-SQL sql-server sql-server

IndexOf function in T-SQL


CHARINDEX is what you are looking for

select CHARINDEX('@', 'someone@somewhere.com')-----------8(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')-----------3(1 row(s) affected)


You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.


One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address