ghost_king
ghost_king

Reputation: 930

Finding records in another table

I wanted to show that a record in one table exists in another table and used the code below. Would this be possible?

CASE WHEN EXISTS (
SELECT  *
FROM    tblA a
        INNER JOIN tblB b ON a.AccountID = b.AccountID
                ) THEN 'YES' ELSE 'NO' END

Upvotes: 0

Views: 52

Answers (2)

dario
dario

Reputation: 5259

Nope. Do something like this instead:

SELECT CASE WHEN (SELECT COUNT(*)
                  FROM tblA AS A
                  INNER JOIN tblB AS B 
                      ON A.AccountID = B.AccountID) > 1
            THEN 'YES' ELSE 'NO' END AS T;

Upvotes: 1

Eduard Uta
Eduard Uta

Reputation: 2607

As Dave Gugg mentioned in his comment that is possible. The alternative is using a LEFT JOIN and for those rows that are not matched in table B display NO, for those that match display YES:

SELECT  a.*, CASE WHEN b.AccountID IS NOT NULL THEN 'YES' ELSE 'NO' END as YesNoCol
FROM    tblA a
LEFT JOIN tblB b ON a.AccountID = b.AccountID

Upvotes: 2

Related Questions