选择是否存在值的布尔结果

时间:2014-12-10 13:11:42

标签: sql sql-server

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

from Table1 

Left join Table2 on Table1.Id=Table2.Id

这就是我目前执行上述要求的方式:

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

from Table1 

Left join Table2 on Table1.Id=Table2.Id

Case”声明是否有替代ifExists(Table2.Id)之类的内容?

2 个答案:

答案 0 :(得分:1)

您可以使用EXISTS,我想您需要字符串True / False,否则将1 / 0投放到bit

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

为了完整起见:

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

答案 1 :(得分:1)

也许你可以使用isNull。

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

 from Table1