If else condition in sql server

By FoxLearn 12/3/2024 11:04:50 PM   81
In SQL Server, the IF ELSE statement is used to execute one block of SQL code if a condition is true, and another block of code if the condition is false.

Syntax: If else condition in sql server

IF condition
BEGIN
    -- SQL statements to execute if the condition is true
END
ELSE
BEGIN
    -- SQL statements to execute if the condition is false
END

For example:

IF NOT EXISTS (SELECT *FROM Customers WHERE CustomerID = @CustomerID)
BEGIN
      INSERT INTO Customers(CustomerID, CustomerName)
END
ELSE
BEGIN
      UPDATE Customers SET CustomerName = @CustomerName WHERE CustomerID = @CustomerID
END

IF NOT EXISTS (SELECT * FROM Customers WHERE CustomerID = @CustomerID): This checks if there are no rows in the Customers table with the given CustomerID. If the result is empty, the INSERT statement will execute.

INSERT INTO Customers(CustomerID, CustomerName): If the customer doesn't exist, this will insert a new row with the specified values.

ELSE: If the CustomerID exists in the table, the UPDATE statement will execute, updating the CustomerName for the customer with the given CustomerID.

The condition is typically an expression that evaluates to true or false. The BEGIN and END keywords are used to group multiple SQL statements together.

You can use the ELSE IF keyword to check for multiple conditions.

For example: if else condition in sql server

DECLARE @Salary INT = 50000;

IF @Salary >= 60000
BEGIN
    PRINT 'The salary is high.';
END
ELSE IF @Salary >= 30000
BEGIN
    PRINT 'The salary is average.';
END
ELSE
BEGIN
    PRINT 'The salary is low.';
END