[sql] 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

The answer is


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.


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 

What the output that you need, select or print or .. so on.

so use the following code:

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

Its best practice to have TOP 1 1 always.

What if I use SELECT 1 -> If condition matches more than one record then your query will fetch all the columns records and returns 1.

What if I use SELECT TOP 1 1 -> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.

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

You can define a variable @Result to fill your data in it

DECLARE @Result AS INT

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

Questions with sql tag:

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database Export result set on Dbeaver to CSV How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? #1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server IF EXISTS THEN 1 ELSE 2 How to add a boolean datatype column to an existing table in sql? Presto SQL - Converting a date string to date format What is the meaning of <> in mysql query? Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Convert timestamp to date in Oracle SQL #1292 - Incorrect date value: '0000-00-00' Postgresql tables exists, but getting "relation does not exist" when querying SQL query to check if a name begins and ends with a vowel Find the number of employees in each department - SQL Oracle Error in MySQL when setting default value for DATE or DATETIME Drop view if exists Could not find server 'server name' in sys.servers. SQL Server 2014 How to create a Date in SQL Server given the Day, Month and Year as Integers TypeError: tuple indices must be integers, not str Select Rows with id having even number SELECT list is not in GROUP BY clause and contains nonaggregated column IN vs ANY operator in PostgreSQL How to insert date values into table Error related to only_full_group_by when executing a query in MySql How to select the first row of each group? Connecting to Microsoft SQL server using Python eloquent laravel: How to get a row count from a ->get() How to execute raw queries with Laravel 5.1? In Oracle SQL: How do you insert the current date + time into a table? Extract number from string with Oracle function Rebuild all indexes in a Database SQL: Two select statements in one query DB2 SQL error sqlcode=-104 sqlstate=42601 What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types How to run .sql file in Oracle SQL developer tool to import database? Concatenate columns in Apache Spark DataFrame How Stuff and 'For Xml Path' work in SQL Server? Fatal error: Call to a member function query() on null

Questions with sql-server tag:

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd SQL Server IF EXISTS THEN 1 ELSE 2 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to add a boolean datatype column to an existing table in sql? How to import an Excel file into SQL Server? How to use the COLLATE in a JOIN in SQL Server? Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Drop view if exists Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to update large table with millions of rows in SQL Server? Could not find server 'server name' in sys.servers. SQL Server 2014 How to create a Date in SQL Server given the Day, Month and Year as Integers Select Rows with id having even number A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233) SQL Server: Error converting data type nvarchar to numeric How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer? Using DISTINCT along with GROUP BY in SQL Server Rebuild all indexes in a Database How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio? The target principal name is incorrect. Cannot generate SSPI context How Stuff and 'For Xml Path' work in SQL Server? How to view the roles and permissions granted to any database user in Azure SQL server instance? How do I create a local database inside of Microsoft SQL Server 2014? Format number as percent in MS SQL Server MSSQL Regular expression How to select all the columns of a table except one column? SQL count rows in a table EXEC sp_executesql with multiple parameters SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Remove decimal values using SQL query How to drop all tables from a database with one SQL query? How to get last 7 days data from current datetime to last 7 days in sql server Get last 30 day records from today date in SQL Server Using Excel VBA to run SQL query No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server How to join two tables by multiple columns in SQL? The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Questions with if-statement tag:

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA Python for and if on one line If "0" then leave the cell blank Python if not == vs if != Simple if else onclick then do? Compare two columns using pandas R - " missing value where TRUE/FALSE needed " Using if-else in JSP How to check the exit status using an if statement How to do one-liner if else statement? Negate if condition in bash script If two cells match, return value from third Multiple IF statements between number ranges Batch - If, ElseIf, Else shorthand c++ if else statement Can dplyr package be used for conditional mutating? how to check for null with a ng-if values in a view with angularjs? How to break a while loop from an if condition inside the while loop? Multiple conditions in if statement shell script The condition has length > 1 and only the first element will be used Excel formula to search if all cells in a range read "True", if not, then show "False" How to include NA in ifelse? Jinja2 template not rendering if-elif-else statement properly Check if a variable is between two numbers with Java Perl - Multiple condition if statement without duplicating code? one line if statement in php break statement in "if else" - java Multiple separate IF conditions in SQL Server Simpler way to check if variable is not equal to multiple string values? How to SUM parts of a column which have same text value in different column in the same row What is a None value? if (boolean condition) in Java IF statement: how to leave cell blank if condition is false ("" does not work) ORA-06502: PL/SQL: numeric or value error: character string buffer too small EXCEL Multiple Ranges - need different answers for each range Regex matching in a Bash if statement IF function with 3 conditions Shorthand for if-else statement One line if/else condition in linux shell scripting Nested ifelse statement Can I use if (pointer) instead of if (pointer != NULL)?

Questions with stored-procedures tag:

How to create temp table using Create statement in SQL Server? How do I pass a list as a parameter in a stored procedure? SQL Server IF EXISTS THEN 1 ELSE 2 Stored procedure with default parameters Could not find server 'server name' in sys.servers. SQL Server 2014 How to kill all active and inactive oracle sessions for user EXEC sp_executesql with multiple parameters MySQL stored procedure return value SQL Server: use CASE with LIKE SQL server stored procedure return a table Loop through all the rows of a temp table and call a stored procedure for each row Default Values to Stored Procedure in Oracle Calling an API from SQL Server stored procedure SQL Server stored procedure Nullable parameter Must declare the scalar variable SQL Server Insert if not exists using stored procedure in entity framework How to call Stored Procedure in Entity Framework 6 (Code-First)? How to run a stored procedure in oracle sql developer? Stored Procedure error ORA-06550 ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error Stored procedure or function expects parameter which is not supplied Cannot bulk load because the file could not be opened. Operating System Error Code 3 Postgres FOR LOOP SQL Server: Invalid Column Name if condition in sql server update query If else in stored procedure sql server How to check if a variable is NULL, then set it with a MySQL stored procedure? Storing query results into a variable and modifying it inside a Stored Procedure How to list all dates between two dates Procedure or function !!! has too many arguments specified Add an incremental number in a field in INSERT INTO SELECT query in SQL Server Using LIKE operator with stored procedure parameters How to produce an csv output file from stored procedure in SQL Server Declare variable MySQL trigger Execute a stored procedure in another stored procedure in SQL server MySQL create stored procedure syntax with delimiter How to debug stored procedures with print statements? SQL Server stored procedure parameters how to write procedure to insert data in to the table in phpmyadmin? Search text in stored procedure in SQL Server MySQL, create a simple function How to execute a stored procedure inside a select query SQL Server stored procedure creating temp table and inserting value How to call Stored Procedures with EntityFramework? Use stored procedure to insert some data into a table Stored Procedure parameter default value - is this a constant or a variable How to debug a stored procedure in Toad? Is it possible to use "return" in stored procedure? How to use If Statement in Where Clause in SQL?

Questions with sql-server-2012 tag:

Count the Number of Tables in a SQL Server Database SQL Server IF EXISTS THEN 1 ELSE 2 Get last 30 day records from today date in SQL Server No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Possible to restore a backup of SQL Server 2014 on SQL Server 2012? SQL Server: Best way to concatenate multiple columns? SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN' SSIS Excel Connection Manager failed to Connect to the Source Sql server - log is full due to ACTIVE_TRANSACTION Index was outside the bounds of the Array. (Microsoft.SqlServer.smo) SQL Server IIF vs CASE System.Data.SqlClient.SqlException: Login failed for user Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0 Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs How to automatically generate unique id in SQL like UID12345678? How to restore a SQL Server 2012 database to SQL Server 2008 R2? The server principal is not able to access the database under the current security context in SQL Server MS 2012 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions Insert Multiple Rows Into Temp Table With SQL Server 2012 Cannot execute script: Insufficient memory to continue the execution of the program Cannot Resolve Collation Conflict Correct way to select from two tables in SQL Server with no common field to join on Convert Date format into DD/MMM/YYYY format in SQL Server Cannot connect to SQL Server named instance from another SQL Server How can I use LTRIM/RTRIM to search and replace leading/trailing spaces? Recover unsaved SQL query scripts How to enable bulk permission in SQL Server SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry Last executed queries for a specific database New Line Issue when copying data from SQL Server 2012 to Excel SQL Server 2012 Install or add Full-text search How can I tell if a VARCHAR variable contains a substring? "No backupset selected to be restored" SQL Server 2012 Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update SQL Server 2012 can't start because of a login failure Enable remote connections for SQL Server Express 2012 Auto increment primary key in SQL Server Management Studio 2012 How do I import a .bak file into Microsoft SQL Server 2012? What is the connection string for localdb for version 11 Where is SQL Server Management Studio 2012? SQL Server Configuration Manager not found Insert/Update/Delete with function in SQL Server Find Locked Table in SQL Server How to check if a column exists in a SQL Server table?