SQL Server IF EXISTS THEN 1 ELSE 2 SQL Server IF EXISTS THEN 1 ELSE 2 sql-server sql-server

SQL Server IF EXISTS THEN 1 ELSE 2


If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') BEGIN   SELECT 1 ENDELSEBEGIN    SELECT 2END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.


How about using IIF?

SELECT IIF (EXISTS (SELECT 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx'), 1, 2)

Also, if using EXISTS to check the the existence of rows, don't use *, just use 1. I believe it has the least cost.


In SQL without SELECT you cannot result anything. Instead of IF-ELSE block I prefer to use CASE statement for this

SELECT CASE         WHEN EXISTS (SELECT 1                      FROM   tblGLUserAccess                      WHERE  GLUserName = 'xxxxxxxx') THEN 1         ELSE 2       END