Checking values row by row

sql, sql-server-2005

Solution

You can use `CASE` and `EXISTS`:

SELECT CatID,
       Name,
       Result = CASE WHEN EXISTS(SELECT 1 
                                 FROM Table2 t2 
                                 WHERE t2.CatID=t1.CatId)
                THEN 'True' ELSE 'False' END
FROM Table1 t1

DEMO

Problem

I have 2 tables like this: Table 1: ``` CatID Name ----- ---- 1 A 2 B 3 C ``` Table 2: ``` ID CatID --- ----- 1 1 2 1 3 1 4 3 ``` Table two CatID is same as the table1 CatID. I want a query which shows the First table with an additional column which says True if CatID exists in the second table or False if not. The output of the above table should be: ``` CatID Name Result ----- ---- ------ 1 A True 2 B False 3 C True ```

Original source