IndexOf function in T-SQL

SqlSql ServerTsqlString

Sql Problem Overview


Given an email address column, I need to find the position of the @ sign for substringing.

What is the indexof function, for strings in T-SQL?

Looking for something that returns the position of a substring within a string.

in C#

var s = "abcde";
s.IndexOf('c'); // yields 2

Sql Solutions


Solution 1 - Sql

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

Solution 2 - Sql

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

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

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

Solution 3 - Sql

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

Solution 4 - Sql

I believe you want to use CHARINDEX. You can read about it here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevelopingChrisView Question on Stackoverflow
Solution 1 - SqlScott IveyView Answer on Stackoverflow
Solution 2 - SqlOMG PoniesView Answer on Stackoverflow
Solution 3 - SqlrichardtallentView Answer on Stackoverflow
Solution 4 - SqlJustin SwartselView Answer on Stackoverflow