SQL Server IF EXISTS THEN 1 ELSE 2

Using Sql Server 2012. I have a stored procedure, and part of it checks to see if the username is in the table. If so, return 1, if not, return 2. This is my code:

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 1 else 2 

However, I keep getting the following error:

Incorrect syntax near '1'.

Is this possible with IF EXIST?

Hi,

Michael

+23
sql sql-server sql-server-2012 stored-procedures if-statement
source share
5 answers

If you want to do it this way, then you need syntax;

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

You don't really need BEGIN..END statements BEGIN..END but it's probably best to get used to this habit from the start.

+53
source share

How about using IIF?

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

Also, if you use EXISTS to check for the existence of strings, do not use *, just use 1. I find this to be the least cost.

+7
source share

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

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

What is the result you need, select or print or .. and so on.

so use the following code:

 IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2 
+3
source share

You can define the @Result variable to populate your data in it

 DECLARE @Result AS INT IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') SET @Result = 1 else SET @Result = 2 
+2
source share

All Articles