If else condition in sql server
By FoxLearn 12/3/2024 11:04:50 PM 81
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 Set Up Dark Theme in SQL Server Management Studio
- DBCC CHECKIDENT RESEED 0
- How to drop temporary table if exists
- How to convert timestamp to date in SQL Server
- How to convert SQL Server's timestamp column to datetime format
- How to convert varchar to uniqueidentifier in SQL Server
- How to Read Excel file and Import data from Excel to SQL Server in C#
- Connection string odbc