Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server IF EXISTS THEN 1 ELSE 2

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

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

However, I keep receiving the below error:

Incorrect syntax near '1'.

Is this even possible with an IF EXIST?

Regards,

Michael

like image 347
Michael Avatar asked Dec 07 '16 10:12

Michael


People also ask

How do you use exists with if in SQL?

The IF EXISTS decision structure will execute a block of SQL code only if an inner query returns one or more rows. If the inner query returns an empty result set, the block of code within the structure is skipped. The inner query used with the IF EXISTS structure can be anything you need it to be.

Is != And <> the same in SQL?

Here is the answer – Technically there is no difference between != and <>. Both of them work the same way and there is absolutely no difference in terms of performance or result.

What can you substitute for if exists in SQL?

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.


3 Answers

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 
END
ELSE
BEGIN
    SELECT 2
END

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

like image 120
Rich Benner Avatar answered Oct 12 '22 09:10

Rich Benner


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.

like image 20
AntDC Avatar answered Oct 12 '22 08:10

AntDC


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 
like image 7
Pரதீப் Avatar answered Oct 12 '22 08:10

Pரதீப்