简体   繁体   中英

SQL Server query to return 1 if value exist in a column else return 0

I am trying to query the database for checking if a specific column has a value or not. If there is a value in that column, the query should return 1, else it should return 0.

But my query is returning the total count of the columns for (ex:10).

Note: query is done in Dell Boomi integration platform, SQL Server.

select count (*) 
from ApplicationRequest 
where EmpID  = '993685' and ApplID = '1';

Do you just want case ?

select (case when count(*) > 0 then 1 else 0 end)
from ApplicationRequest
where EmpID = 993685 and ApplID = 1;

I removed the single quotes around the comparisons. If they are really numbers then single quotes are not appropriate. If they are indeed strings, then use the single quotes.

If this is what you want, a more efficient method would use exists :

select (case when exists (select 1 
                          from ApplicationRequest
                          where EmpID = 993685 and ApplID = 1
                         )
             then 1 else 0
        end)

The aggregation query needs to find all matching rows. This version can stop at the first one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM