如何使用SQL Select语句和IF EXISTS子查询?
如何使用IF EXISTS语句(SQL Server)从子查询中select布尔值?
它应该是这样的:
SELECT TABEL1.Id, NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID) SELECT 'TRUE' ELSE SELECT 'FALSE') FROM TABEL1
使用CASE
:
SELECT TABEL1.Id, CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID) THEN 'TRUE' ELSE 'FALSE' END AS NewFiled FROM TABLE1
如果TABLE2.ID
是唯一的或主键,您也可以使用这个:
SELECT TABEL1.Id, CASE WHEN TABLE2.ID IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END AS NewFiled FROM TABLE1 LEFT JOIN Table2 ON TABLE2.ID = TABLE1.ID
你也可以使用ISNULL和一个select语句来得到这个结果
SELECT Table1.ID, ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName, etc FROM TABLE1
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1 INTERSECT SELECT Id, 'TRUE' AS NewFiled FROM TABEL2 UNION SELECT Id, 'FALSE' AS NewFiled FROM TABEL1 EXCEPT SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
使用CASE
语句,像这样做:
SELECT T1.Id [Id] ,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2] FROM TABLE1 [T1] LEFT OUTER JOIN TABLE2 [T2] ON T2.Id = T1.Id