I have two tables:
Table 1: CustomerEmails:
CREATE TABLE [dbo].[CustomerEmails](
[id] [int] IDENTITY(1,1) NOT NULL,
[datecreated] [datetime] NULL,
[UID] [nvarchar](250) NULL,
[From] [nvarchar](100) NULL,
[To] [nvarchar](100) NULL,
[Subject] [nvarchar](max) NULL,
[Body] [nvarchar](max) NULL,
[Dated] [datetime] NULL,
CONSTRAINT [PK_CustomerEmails] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)
Table 2: CustomerEmailIds:
CREATE TABLE [dbo].[CustomerEmailIds](
[Email] [varchar](200) NULL
) ON [PRIMARY]
You may be thinking that why i am not using the EmailId in table CustomerEmails instead of using the emails itself? what i mean is that i can add a column EmailId (INT) to the table CustomerEmailIds & then i can refer that column instead of CustomerEmails.From & CustomerEmails.To?? Guys the issue is the table CustomerEmails is used by some other application & that application just keeps the track of emails sent/received through OutLook. The table CustomerEmailIds have customer emails & these emails come into system from the application i am working on.
So the Table CustomerEmails have 7,00,000+ records while table CustomerEmailIds have 1,00,000+ records.
I need to find out the emails from table CustomerEmails, based on the emails in CustomerEmailIds table.
The query i am using is:
SELECT
e.*
FROM CustomerEmails e
WHERE EXISTS
(
SELECT Email
FROM CustomerEmailIds c
WHERE ( ISNULL(e.[From],'') + '/' + ISNULL(e.[To],'') ) LIKE '%'+c.Email+'%'
)
Some facts:
1- I am using SQL Server 2008
2- Sorry guys, i forgot to mention that the CustomerEmails.**To** can contains multiple comma separated emails like: email1@yahho.com,email2@yahho.com,email3@yahho.com
3- Because of the fact2 the c.Cs3Emails+'%' OR to= c.Cs3Emails will not list the desired results that's why i am using '%'+c.Cs3Emails+'%'
Latest Findings:
Guys the above query return wrong results….. & i don’t know why??
But below query works fine:
SELECT
e.*
FROM CustomerEmails e
WHERE (ISNULL(e.[From],'') + '/' + ISNULL(e.[To],'')) LIKE '%email1@gmail.com%'
Well guys first look at the query which is returning the wrong results:
There is no issue in this query, the issue is that some of the emails in CustomerEmailIds table are invalid emails which are (‘.’,’@’,’0′,’-‘) & that’s why the query is returning all the CustomerEmails where these invalid emails exists.
Thanks to Kev Riley! the persons who helped me find out the cause of this issue here!