Saturday, June 18, 2011

SQL SERVER – Selecting Domain from Email Address


Recently I came across a quick need where I needed to retrieve domain of the email address. The email address is in the database table. I quickly wrote following script which will extract the domain and will also count how many email addresses are there with the same domain address.
SELECT RIGHT(EmailLEN(Email) - CHARINDEX('@'email)) Domain ,COUNT(EmailEmailCountFROM   dbo.emailWHERE  LEN(Email) > 0GROUP BY RIGHT(EmailLEN(Email) - CHARINDEX('@'email))ORDER BY EmailCount DESC
Above script will select the domain after @ character. Please note, if there is more than one @ character in the email, this script will not work as that email address is already invalid.

No comments: