If else condition in sql server
By Tan Lee Published on Dec 03, 2024 309
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
- How to Download ODBC Driver for SQL Server
- How to Download SQL Server Management Studio (SSMS) Versions
- How to Query JSON in SQL Server
- How to modify JSON in SQL Server
- How to set time to 00:00:00 with GETDATE() in SQL
- How to find all the dependencies of a table in SQL Server
- How to Find Objects Referencing a Table in SQL Server
- Case sensitivity in SQL Server