178

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
BoffinBrain
  • 6,337
  • 6
  • 33
  • 59
DevelopingChris
  • 39,797
  • 30
  • 87
  • 118

4 Answers4

262

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)
Scott Ivey
  • 40,768
  • 21
  • 80
  • 118
73

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.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
37

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

richardtallent
  • 34,724
  • 14
  • 83
  • 123
  • these are the kinds of things that I'm trying to determine and fix in our database. Mainly people just mis type their domain name. most web redirect back to the real one but the mx records don't forward, and displaying them gets awkward – DevelopingChris Dec 13 '09 at 06:50
  • There's a special place in heck for people who put @'s in the first part of their email addresses ... like people who put spaces in table/field names ... – DavidMWilliams Apr 28 '22 at 04:36
11

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

Justin Swartsel
  • 3,451
  • 1
  • 20
  • 24