If else condition in sql server
By FoxLearn 12/3/2024 11:04:50 PM 191
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 and Restore Northwind database to SQL Server
- How to set time to 00:00:00 with GETDATE() in SQL
- Restoring MySQL Databases with mysqldump
- How to use Oracle linked server shows all tables
- Download backup of Northwind database for SQL Server
- How to Convert varchar to uniqueidentifier in SQL Server
- How to fix 'The transaction log for the database is full due to ACTIVE_TRANSACTION'
- How to use ROW_NUMBER Function in SQL Server