If else condition in sql server
By FoxLearn 12/3/2024 11:04:50 PM 134
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 fix 'The transaction log for the database is null due to OLDEST_PAGE'
- How to convert varchar to uniqueidentifier in SQL Server
- How to convert timestamp to date in SQL Server
- How to Download and Restore Northwind database to SQL Server
- How to Download Microsoft SQL Server
- Saving changes is not permitted in SQL Server
- How to change ‘Edit Top 200 Rows’ and ‘Select Top 1000 Rows’ in SQL
- How to fix 'The specified sa password does not meet strong password requirements'