How to select Boolean value from sub query with IF EXISTS statement (SQL Server)?
It should be something like :
SELECT TABEL1.Id, NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID) SELECT 'TRUE' ELSE SELECT 'FALSE') FROM TABEL1
A subquery-also referred to as an inner query or inner select-is a SELECT statement embedded within a data manipulation language (DML) statement or nested within another subquery. You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed.
The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement. Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name(s) FROM table_name WHERE condition);
An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
Use 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
If TABLE2.ID
is Unique or a Primary Key, you could also use this:
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
You can also use ISNULL and a select statement to get this result
SELECT Table1.ID, ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName, etc FROM TABLE1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With