Click here to Skip to main content
15,885,180 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Experts,

I have 2 tables (customers, users) each of them has [Email] Field, no common fields to join.
I want to be able to check if a given email exists in either one, something like:

SQL
select Id from customers where customers.email='email' or user.email='email'
OR
return true if @email exists in (customers or users)


looking for the correct syntax.

Thanks in advance!
Samira
Posted

An alternative would be to union the email addresses e.g.
SQL
DECLARE @Result int

--Dummy data
declare @tbl1 table (id1 int identity(1,1), email1 varchar(30))
declare @tbl2 table (id2 int identity(1,1), email2 varchar(30))
insert into @tbl1  values('email1'),('email2'),('email3')
insert into @tbl2  values('email4'),('email2'),('email5')

if exists (select top 1 * from (select email1 from @tbl1 union select email2 from @tbl2) t where email1=@email)
    set @Result= 1
else
    set @Result= 0

 return @Result
 
Share this answer
 
Comments
Samira Radwan 26-Aug-15 12:03pm    
Thanks! that works.
Andy Lanng 26-Aug-15 12:27pm    
Alright, smarty-pants. You get a 5* :P
Samira Radwan 26-Aug-15 12:29pm    
got 5* ^_^
Maciej Los 26-Aug-15 15:47pm    
Very interesting, Caroline. +5!
Please, see my solution ;)
Another way is to use pivot table this way:

SQL
SELECT TableName, [Customers], [User] 
FROM (
    SELECT 'Customers' AS TableName, ID, Email
    FROM Customers
    UNION ALL
    SELECT 'User' AS TableName, ID, Email
    FROM User
) AS DT
PIVOT (MAX(ID) FOR TableName IN ([Customers], [User])) AS PT
WHERE Email = @email
 
Share this answer
 
best use a couple of simple "not exists"

SQL
declare @email nvarchar(max)
set @email = 'me@mine.com'

IF  not exists (select * from customers where customers.email=@email) 
and not exists (select * from users where users.email=@email) 
  return 1
else
  return 0

hope that helps ^_^
Andy
 
Share this answer
 
v3
Comments
Samira Radwan 26-Aug-15 10:35am    
Thanks Andy, I think your query has syntax error. I had to add if before the first (not) but still. Incorrect syntax near ')' the last brackets. Any idea why?
Andy Lanng 26-Aug-15 10:38am    
Oh - copy-paste error - The second line should read users.email=@email
:P
No need for an if. pointless to say "if(this) return true else return false". Should just be able to return 'this' ('this' being the logic query). I could be wrong though :/
CHill60 26-Aug-15 10:41am    
Not convinced return works like that in sql
Andy Lanng 26-Aug-15 10:47am    
me neither, but hopefully the OP will work it out and let us know ^_^
Herman<T>.Instance 26-Aug-15 10:41am    
Why declare nvarchar(max) if only 11 chars are needed?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900