Nov 29, 2009

Validate Email Addresses in SQL Server


I will be honest here – doing email address validation in SQL Server is one of the most challenging tasks a T-SQL programmer faces.

Stefan Plattner sometime back on the forums shared a query to validate Email Address. I have been using this query in my applications and thought of sharing this with all of you

Let us create a sample table

DECLARE @TT table
(
ID smallint,
StudentID smallint,
EA nvarchar(30)
)

-- Create Sample Data
INSERT INTO @TT VALUES ( 101, 1, 'jill@abcdef.com');
INSERT INTO @TT VALUES ( 102, 2, 'matt@abcdef.com');
INSERT INTO @TT VALUES ( 103, 3, 'abcdef.com');
INSERT INTO @TT VALUES ( 104, 4, '@abcdef@deamon.com');
INSERT INTO @TT VALUES ( 105, 5, 'carlos@abcdef.com');
INSERT INTO @TT VALUES ( 106, 6, 'sachin@abcdef.com');
INSERT INTO @TT VALUES ( 107, 7, 'terri.jake@abcdef.com');
INSERT INTO @TT VALUES ( 108, 8, 'triplet@@abcdef.com');
INSERT INTO @TT VALUES ( 109, 9, 'robert@abcdef.com');
INSERT INTO @TT VALUES ( 110, 10, 'bill@abcdef.com');

Now write the query to print valid email addresses

-- Print Valid Email Addresses
SELECT * FROM @TT WHERE
CHARINDEX
(' ',LTRIM(RTRIM(EA))) = 0
AND LEFT(LTRIM(EA),1) <> '@'
AND RIGHT(RTRIM(EA),1) <> '.'
AND CHARINDEX('.',EA , CHARINDEX('@',EA))- CHARINDEX('@',EA ) > 1
AND LEN(LTRIM(RTRIM(EA )))- LEN(REPLACE(LTRIM(RTRIM(EA)),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(EA)))) >= 3
AND (CHARINDEX('.@',EA ) = 0
AND CHARINDEX('..',EA ) = 0)

OUTPUT

image

As you can see the query eliminates email addresses of ID 103, 104 and 108 since they are invalid.

Submit this story to DotNetKicks

Related Posts In This Category



Widget by Hoctro | Jack Book

 
  Feedback:

comments

2 Responses to "Validate Email Addresses in SQL Server"
  1. Madhivanan said...
    February 3, 2010 5:42 AM

    Suprotim

    Isn't it possible to add code tag so that when we copy the code and paste in Query analyser they appear as they are instead of everything in a single line (which obviously need rework formatting the code)?

    Madhivanan
    http://beyondrelational.com/blogs/madhivanan

  2. Suprotim Agarwal said...
    February 3, 2010 6:59 PM

    Madhivanan,

    Yes I know about this issue. Do you know of a plugin that lets you format code with Live Writer?

 

Copyright 2009 All Rights Reserved SQL Server Curry by Suprotim Agarwal