user3340627
user3340627

Reputation: 3143

Select boolean result of whether a value exists or not

Select FieldA, " if data exists in table two return true else false "

from Table1 

Left join Table2 on Table1.Id=Table2.Id

This is how I currently do the requirement above:

Select FieldA, (case when Table2.Table2Id is not null then 1 else 0 End)

from Table1 

Left join Table2 on Table1.Id=Table2.Id

Is there any replacement for the "Case" statement, to something like ifExists(Table2.Id) ?

Upvotes: 0

Views: 72

Answers (2)

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

May be you can use isNull as well.

Select FieldA, isnull((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName

 from Table1 

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use EXISTS, i guess you want the strings True/False, otherwise cast 1/0 to bit:

SELECT Id,
       DataExists = CASE WHEN EXISTS
       (
           SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
       ) THEN 'True' ELSE 'False' END
FROM dbo.Table1

For the sake of completeness:

SELECT Id,
       DataExists = CAST((CASE WHEN EXISTS
       (
           SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
       ) THEN 1 ELSE 0 END) AS BIT)
FROM dbo.Table1

Upvotes: 1

Related Questions